Skip to content

C# Custom Indexers

25 February 2009

To add an indexer to a class, similar to the ones on Dictionary or List for example, all you need to do is to create a property object this[object indexer]. For example:

class MyClass
{
    public string this[int index]
    {
        get
        {
            return "Hello world!";
        }
    }
}

The class can now be indexed using an integer and returns a string (“Hello world!” in our case). An example of using this indexer:

class Program
{
    static void Main(string[] args)
    {
        MyClass myClass = new MyClass();


        Console.WriteLine(myClass[10]);
    }
}

Indexing an instance of MyClass with any value yelds our string. Of course, any types can be used as indexer and returend values. And it is enough to implement a setter ( set { } ) to enable attributing to the indexed element.

From → code complete

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: