views:

54

answers:

3

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];
    }
}
+2  A: 

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 = myFood.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]; }
}
Justin Niessner
+5  A: 

No - you can't write named indexers in C#. As of C# 4 you can consume them for COM objects, but you can't write them.

As you've noticed, however, foo.Bars[index] will do what you want anyway... this answer was mostly for the sake of future readers.

Jon Skeet
Could you not copy the same style used here http://msdn.microsoft.com/en-us/library/146h6tk5.aspx and depending on how you implement the method get the same result?
Gage
@Gage: I'm not sure what you're saying here... that doesn't create a named indexer as far as I can see...
Jon Skeet