Is it possible to have something like the following:
class C
{
public Foo Foos[int i]
{
...
}
public Bar Bars[int i]
{
.
This from C# 3.0 spec
"Overloading of indexers permits a class, struct, or interface to declare multiple indexers, provided their signatures are unique within that class, struct, or interface."
public class MultiIndexer : List<string>
{
public string this[int i]
{
get{
return this[i];
}
}
public string this[string pValue]
{
get
{
//Just to demonstrate
return this.Find(x => x == pValue);
}
}
}
C# doesn't have return type overloading. You can define multiple indexers if their input parameters are different.
Try my IndexProperty class to enable multiple indexers in the same class
http://www.codeproject.com/Tips/319825/Multiple-Indexers-in-Csharp
Not in C#, no.
However, you can always return collections from properties, as follows:
public IList<Foo> Foos
{
get { return ...; }
}
public IList<Bar> Bars
{
get { return ...; }
}
IList<T> has an indexer, so you can write the following:
C whatever = new C();
Foo myFoo = whatever.Foos[13];
On the lines "return ...;" you can return whatever implements IList<T>, but you might what to return a read-only wrapper around your collection, see AsReadOnly() method.
If you're trying to do something like this:
var myClass = new MyClass();
Console.WriteLine(myClass.Foos[0]);
Console.WriteLine(myClass.Bars[0]);
then you need to define the indexers on the Foo and Bar classes themselves - i.e. put all the Foo objects inside Foos, and make Foos a type instance that supports indexing directly.
To demonstrate using arrays for the member properties (since they already support indexers):
public class C {
private string[] foos = new string[] { "foo1", "foo2", "foo3" };
private string[] bars = new string[] { "bar1", "bar2", "bar3" };
public string[] Foos { get { return foos; } }
public string[] Bars { get { return bars; } }
}
would allow you to say:
C myThing = new C();
Console.WriteLine(myThing.Foos[1]);
Console.WriteLine(myThing.Bars[2]);
No you cant do it. Only methods that can have their signatures differ only by return type are conversion operators. Indexers must have different input parameter types to get it to compile.