red-question-mark

Overload the array square bracket operator in C#

Although operator overloading is possible in C# (just like in C++), overloading the array square bracket operator is by definition not possible.  However, C# provides an alternative called Indexers (C# Programming Guide).

This is directly from the Microsoft C# Reference for the [] Operator:

The array indexing operator cannot be overloaded; however, types can define indexers, and properties that take one or more parameters. Indexer parameters are enclosed in square brackets, just like array indexes, but indexer parameters can be declared to be of any type, unlike array indexes, which must be integral.

The syntax for indexers resembles the C# syntax for properties rather than its syntax for operator overloading. Here’s a quick snippet for providing array-like access to a List you’d like to keep hidden within a class:

// overloads the square brackets to provide array-like access.
public T this[int i]
{
    get { return this.List[i]; }
    set { this.List[i] = value; }
}

Worked for me, and hopefully it works just as well for you!

UPDATE: As I do a quick search now, this Stack Overflow post just turned up.


About the Author
Avatar

Ray Li

Ray is a software engineer and data enthusiast who has been blogging for over a decade. He loves to learn, teach and grow. You’ll usually find him wrangling data, programming and lifehacking.

Comments 1

  1. Avatar

Leave a Reply

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

ten + 7 =

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