How to write a class that (like array) can be indexed with `arr[key]`?

Riz picture Riz · Jul 24, 2011 · Viewed 15k times · Source

Like we do Session.Add("LoginUserId", 123); and then we can access Session["LoginUserId"], like an Array, how do we implement it?

Answer

jakebasile picture jakebasile · Jul 24, 2011

You need an indexer:

public Thing this[string index]
{
    get
    {
         // get the item for that index.
         return YourGetItemMethod(index)
    }
    set
    {
        // set the item for this index. value will be of type Thing.
        YourAddItemMethod(index, value)
    }
}

This will let you use your class objects like an array:

MyClass cl = new MyClass();
cl["hello"] = anotherObject;
// etc.

There's also a tutorial available if you need more help.

Addendum:

You mention that you wanted this to be available on a static class. That get's a little more complicated, because you can't use a static indexer. If you want to use an indexer, you'd need to access it off of a static Field or some such sorcery as in this answer.