Indexer (Programming)

From Handwiki

In object-oriented programming, an indexer allows instances of a particular class or struct to be indexed just like arrays.[1] It is a form of operator overloading.

Implementation

Indexers are implemented through the get and set accessors for the

operator[]

. They are similar to properties, but differ by not being 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

value

parameter.

Example

Here is a C# example of the usage of an indexer in a class: [2]

class Family
{
    private List<string> _familyMembers = new List<string>();

	public Family(params string[] members)
	{
	    _familyMembers.AddRange(members);
	}

	public string this[int index]
	{
		// The get accessor
		get => _familyMembers[index];

		// The set accessor with 
		set => _familyMembers[index] = value;
	}

	public int this[string val]
	{
		// Getting index by value (first element found)
		get => _familyMembers.FindIndex(m => m == val);
	}

	public int Length => _familyMembers.Count;
}

Usage example:

void Main()
{
    var doeFamily = new Family("John", "Jane");
    for (int i = 0; i < doeFamily.Length; i++)
    {
        var member = doeFamily[i];
        var index = doeFamily[member]; // same as i in this case, but it demonstrates indexer overloading allowing to search doeFamily by value.
        Console.WriteLine($"{member} is the member number {index} of the {nameof(doeFamily)}");
    }
}

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

  • Mutator method

References

  1. jagadish980 (2008-01-29). "C# - What is an indexer in C#". http://forums.sureshkumar.net/vb-asp-net-interview-technical-questions/16320-c-what-indexer-c.html. 
  2. "C# Interview Questions". https://www.dotnetfunda.com/interview/exam4161-what-is-an-indexer-in-csharp-.aspx. 




Retrieved from "https://handwiki.org/wiki/index.php?title=Indexer_(programming)&oldid=2642000"

Categories: [Programming language topics] [Object-oriented programming] [Operators (programming)]


Download as ZWI file | Last modified: 02/26/2024 22:42:24 | 14 views
☰ Source: https://handwiki.org/wiki/Indexer_(programming) | License: CC BY-SA 3.0

ZWI is not signed. [what is this?]