Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to overload the square bracket operator in C#?

Posted on: 2011-11-03

To overload a square bracket in C# simple. In fact, I am writing this because most example show you this :

  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.