Home » C# » How to overload the square bracket operator in C#?

How to overload the square bracket operator in C#?

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.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.