Indexer (programming): Difference between revisions

Content deleted Content added
Example: 4-space indention
Extended the existing code showing how the indexer can be used by turning it into a working example.
Line 17:
class OurFamily
{
public OurFamily(params string[] pMembers)
private long[] familyMember = new long[7];
{
public long this [int index]
familyMembers = new List<string>();
{
familyMembers.AddRange(pMembers);
// The get accessor
}
get
{
private List<string> familyMembers;
return familyMember[index];
}
public longstring this [int index]
{
// The get accessor
get
{
return familyMemberfamilyMembers[index];
}
 
// The set accessor with
set
{
{
familyMemberfamilyMembers[index] = value;
}
}
}
 
public int this[string val]
{
// Getting index by value (first element found)
get
{
return familyMembers.FindIndex(m => m == val);
}
}
 
public int Length => familyMembers.Count;
}
</source>
 
Usage example:
 
<source lang="csharp">
void Main()
{
var doeFamily = new OurFamily("John", "Jane");
for (int i = 0; i < doeFamily.Length; i++)
{
var member = doeFamily[i];
var index = doeFamily[member];
Console.WriteLine($"{member} is the member number {index} of the {nameof(doeFamily)}");
}
}
</source>
 
In this example, the indexer is used to get the value at the nth position, and then to get the position in the list referenced by its value.
The output of the code is:
John is the member number 0 of the doeFamily
Jane is the member number 1 of the doeFamily
 
== See also ==