Overloading the indexer operator in C#

There’s a feature in C# that’s very useful for some use cases, yet many people seem to overlook it. I’m talking about the indexer operator. What this operator does is, it makes it possible to access elements of an enumerable data structure that your class makes use of, with the familiar [] operator.

Let’s say we have a class named Car:

Now let’s say that we have multiple cars, multiple instances of the class Car and that we want to organize them in a collection. What should we use? A plain old Generic List you might say and you would be correct, but what happens if we want to augment that list with more operations, more car-specific operations. Perhaps we want to clean the cars, or repair them. All that logic can nicely go inside a class named Garage:

As you can see we still use a List to store the cars, but we’re using the delegate pattern. A generic list has a bunch of methods but we only need three of them, the Add(), ElementAt() and Remove() methods. Oh and we also need the Count property so that we know how many cars we have.

This is an initial draft of our garage class showing the use of the delegate pattern. We can also include other stuff to make the class resemble real-life garage even more

The addition of the Clean() and Repair() methods improves our Garage implementation but there’s something missing. Every time we want to access a specific car by index we are forced to use the Get() method. It’s counter-intuitive. Here’s where the powerful indexer operator comes into play. After we’ve implemented an indexer operator in our collection class we will be able to access car elements with array-like syntax, like this:

Let’s see how simple it is to do that

So basically, you override the indexer operator like a property, with a getter and a setter. In this particular example we don’t want to be able to manipulate the contents of the garage so we don’t need a setter. But using a setter is a totally legitimate operation and one you will probably find pretty helpful once you start using it. That’s how easy it is 🙂

Check the whole project on this GitHub repo