Indexer

from Wikipedia, the free encyclopedia

In object-oriented programming , an indexer allows instances of a class or structure to be indexed in the same way as arrays . It is a type of operator overloading .

implementation

Indexers are implemented in C # using get and set accessors . They are similar to properties, but the difference is that they are not static and that accessors require parameters. They are called like methods, with both accessors using the index as a parameter, while the set accessor also has the implicit value parameter for assigning a value.

example

An example in C # illustrates the use of an indexer in a class:

class OurFamily
{
	public OurFamily(params string[] pMembers)
	{
	    familyMembers = new List<string>();
	    familyMembers.AddRange(pMembers);
	}

	private List<string> familyMembers;

	public string this[int index]
	{
		// Der get accessor
		get
		{
		    return familyMembers[index];
		}

		// Der set accessor
		set
		{
		    familyMembers[index] = value;
		}
	}

	public int this[string val]
	{
		// Index über den Wert ermitteln (das erste gefundene Element)
		get
		{
		    return familyMembers.FindIndex(m => m == val);
		}
	}

	public int Length => familyMembers.Count;

}

Example of usage:

void Main()
{
    var doeFamily = new OurFamily("John", "Jane");
    for (int i = 0; i < doeFamily.Length; i++)
    {
        var member = doeFamily[i];
        var index = doeFamily[member]; // in diesem Fall wie i, aber es soll gezeigt werden, wie man den Index eines Wertes sucht.
        Console.WriteLine($"{member} is the member number {index} of the {nameof(doeFamily)}");
    }
}

In this example, the indexer is used to find the value in the ith digit and then to determine the position of a value. The sample program outputs the following:

  John is the member number 0 of the doeFamily
  Jane is the member number 1 of the doeFamily

Individual evidence

  1. jagadish980: C # - What is an indexer in C # . Bulletin: SURESHKUMAR.NET FORUMS. January 29, 2008. Archived from the original on September 22, 2009. Retrieved on August 1, 2011.
  2. C # Interview Questions . .net Funda. Retrieved August 1, 2011.