Implementing an indexer for your object with C# .NET

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.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Implementing an indexer for your object with C# .NET

  1. Pingback: Implementing an indexer for your object with C# .NET | Dinesh Ram Kali.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: