Indexer (programming): Difference between revisions

Content deleted Content added
Dmt137 (talk | contribs)
Implementation: added Python example
Dmt137 (talk | contribs)
m C sharp: added csharp "vector" example
Line 26:
Indexers are implemented through the get and set [[Mutator method|accessor]]s for the {{C_sharp|operator[]}}. They are similar to [[Property (programming)|properties]], but differ by not being [[Static method|static]], and the fact that indexers' accessors take parameters. The get and set accessors are called as methods using the parameter list of the indexer declaration, but the set accessor still has the implicit {{C_sharp|value}} parameter.
 
==== Example 1====
<syntaxhighlight lang="csharp">
public class vector{
private double[] data;
public vector(int n){data = new double[n];}
public int size => data.Length;
public double this[int i]{ get => data[i]; set => data[i]=value;}
 
public static void Main(){
var v=new vector(3);
for(int i=0;i<v.size;i++) v[i]=i+1;
for(int i=0;i<v.size;i++) System.Console.WriteLine(v[i]);
}
}
</syntaxhighlight>
 
==== Example 2====
Here is a C# example of the usage of an indexer in a class:
<ref>{{cite web