How to overload the square bracket operator in C#?<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to overload the square bracket operator in C#?

Posted on: November 3, 2011

This is pretty simple. In fact, I am writing this because most example show you this :

public object this[int index] { get { return collection[index]; } set { collection[index] = value; } }

In fact, you should return the type of your collection. So, if your object contains a collection of Person than you should write :

public Person this[int index] { get { return collection[index]; } set { collection[index] = value; } }

This way, the value returned doesn't require to be casted.