Explicit interface indexer implementations?

J

Jon Rista

Is there a way to explicityly implement an interfaces indexer? I need to
create a collection class, that implements IList, ICollection, and
IEnumerable. I'd like to create a custom indexer, with a return value of my
choosing, rather than object. Whenever I try, though, the compiler spits out
an error (I use C#, BTW). I've tried simply implementing object this[int
index] in addition to MyClass this[int index], but got an error. I also
tried IList.this[int index] in addition to MyClass this[int index] but also
got an error. How does one explicityly implement the indexer of an interface
so you can implement a custom one? Thanks for the help.

Jon Rista
 
J

Jon Skeet

Jon Rista said:
Is there a way to explicityly implement an interfaces indexer? I need to
create a collection class, that implements IList, ICollection, and
IEnumerable. I'd like to create a custom indexer, with a return value of my
choosing, rather than object. Whenever I try, though, the compiler spits out
an error (I use C#, BTW). I've tried simply implementing object this[int
index] in addition to MyClass this[int index], but got an error. I also
tried IList.this[int index] in addition to MyClass this[int index] but also
got an error. How does one explicityly implement the indexer of an interface
so you can implement a custom one? Thanks for the help.

It works fine for me:

using System;

interface Foo
{
string this[int i]
{
get;
}
}

class Test : Foo
{
string Foo.this[int i]
{
get { return "interface"; }
}

int this[int i]
{
get { return 1; }
}


static void Main(string[] args)
{
Test t = new Test();
Console.WriteLine (t[0]);
Foo f = t;
Console.WriteLine (f[0]);
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top