Reputation: 40507
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
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
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
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:
Upvotes: 15
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
Reputation: 18203
You can roll your own "named indexer" however. See
Upvotes: 1