Search code examples
c#propertiesindexed-properties

Is named indexer property possible?


Suppose I have an array or any other collection for that matter in class and a property which returns it like following:

public class Foo
{
    public IList<Bar> Bars{get;set;}
}

Now, may I write anything like this:

public Bar Bar[int index]
{
    get
    {
        //usual null and length check on Bars omitted for calarity
        return Bars[index];
    }
}

Solution

  • Depending on what you're really looking for, it might already be done for you. If you're trying to use an indexer on the Bars collection, it's already done for you::

    Foo myFoo = new Foo();
    Bar myBar = myFoo.Bars[1];
    

    Or if you're trying to get the following functionality:

    Foo myFoo = new Foo();
    Bar myBar = myFoo[1];
    

    Then:

    public Bar this[int index]
    {
        get { return Bars[index]; }
    }