TheVillageIdiot
TheVillageIdiot

Reputation: 40507

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];
    }
}

Upvotes: 8

Views: 7941

Answers (5)

Justin Niessner
Justin Niessner

Reputation: 245429

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]; }
}

Upvotes: 0

Doug
Doug

Reputation: 11

public class NamedIndexProp
{
    private MainClass _Owner;
    public NamedIndexProp(MainClass Owner) { _Owner = Owner;
    public DataType this[IndexType ndx]
    {
        get { return _Owner.Getter(ndx); }
        set { _Owner.Setter(ndx, value); }
    }
}
public MainClass
{
    private NamedIndexProp _PropName;
    public MainClass()
    {
       _PropName = new NamedIndexProp(this);
    }
    public NamedIndexProp PropName { get { return _PropName; } }
    internal DataType getter(IndexType ndx)
    {
        return ...
    }
    internal void Setter(IndexType ndx, DataType value)
    {
       ... = value;
    }
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500675

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.

To elaborate: exposing a Bars property of some type that has an indexer achieves what you want, but you should consider how to expose it:

  • Do you want callers to be able to replace the collection with a different collection? (If not, make it a read-only property.)
  • Do you want callers to be able to modify the collection? If so, how? Just replacing items, or adding/removing them? Do you need any control over that? The answers to those questions would determine what type you want to expose - potentially a read-only collection, or a custom collection with extra validation.

Upvotes: 15

George Birbilis
George Birbilis

Reputation: 2930

You can use explicitly implemented interfaces, as shown here: Named indexed property in C#? (see the second way shown in that reply)

Upvotes: 1

cdiggins
cdiggins

Reputation: 18203

You can roll your own "named indexer" however. See

Upvotes: 1

Related Questions