Implementing an indexer for your object with C# .NET
December 8, 2016 Leave a comment
Indexers are used extensively when accessing items in an array or List:
Friend f = friends[2];
It’s fairly easy to implement your own indexer. Imagine a table with guests sitting around. We could implement an indexer to easily access guest #n.
The Guest object is simple with only one property:
public class Guest
{
public string Name { get; set; }
}
Here comes the implementation of the Table object including the indexers:
public class Table
{
public Table()
{
Guests = new List<Guest>()
{
new Guest(){Name = "John"}
, new Guest(){Name = "Charlie"}
, new Guest() {Name = "Jill"}
, new Guest(){Name = "Jane"}
, new Guest(){Name = "Martin"}
, new Guest(){Name = "Ann"}
, new Guest(){Name = "Eve"}
};
}
private List<Guest> Guests { get; set; }
public Guest this[int index]
{
get
{
return Guests[index];
}
set
{
Guests[index] = value;
}
}
public Guest this[string index]
{
get
{
return (from g in Guests where g.Name.ToLower() == index.ToLower() select g).FirstOrDefault();
}
}
}
Let’s see what we have here:
- A constructor that fills up the private Guests list
- An integer indexer with get and set methods. This looks like a standard getter and setter property. The getter returns the Guest from the list in position “index”. The setter sets the incoming guest – value – at the appropriate index
- A string indexer that allows to extract a guest by a name
Here’s how you can call the indexers:
public class CustomIndexerService
{
public void RunDemo()
{
Table t = new Table();
Guest guest = t[2];
Guest replacement = new Guest() { Name = "Elvis" };
t[1] = replacement;
Guest martin = t["martin"];
}
}
We first extract Guest #2 which returns Jill as arrays start at 0. We then replace Guest #1 with another guest Elvis. Finally we retrieve the guest “Martin” using the string indexer.
View all various C# language feature related posts here.