C# Indexers and how to use them

Indexers in C# are used quite a bit for collections, for example:

List<string> list = new List<string> { "a", "b", "c" };
string value = list[1]; // This is using an indexer

Dictionary<string, string> dictionary = new Dictionary<string, string>
    { "foo", "bar" },
    { "x", "y" }
string value = dictionary["x"]; // This is using an indexer

But how do you implement one for your own class? Have a look at my AddressBook class.

public class AddressBook
        private List<Address> Addresses;
        public int AddressBookSize { get { return Addresses.Count(); } }

        public Address this[int index]
                return Addresses[index];
                Addresses[index] = value;

        public AddressBook()
            Addresses = GoToDatabaseOrServiceAndGetAddressList();

Notice how I create a public variable of type Address called this that exposes our private address list and gets and sets values to it. This is essentially an indexer.

Here is how I can use my AddressBook class making use of our indexer.

class Program
        static void Main(string[] args)
            var addressBook = new AddressBook();

            // use the indexer to update the address at index 2
            addressBook[2] = new Address()
                HouseNumber = "X",
                HouseName = "Foo",
                Street = "Y Road",
                County = "Co.Z"

            for (int i = 0; i < addressBook.AddressBookSize; i++)
                // access address variables such as house number & name, you can even access functions this way
                Console.WriteLine("{0} {1}, {2}, {3}", 

            // to keep console window open

Source: Real world use cases for C# indexers?


Published by

Alan Feekery

Developer, Gamer, Musician, Cyclist and big Motorsport fan... enjoys the odd cup of coffee :)

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s