Christophe Debove
Christophe Debove

Reputation: 6296

How to define Indexer behaviour to an Interface?

Is it possible to add the indexer behaviour from an interface?

something like this :

interface IIndexable<T>
{
   T this[string index];
}

Upvotes: 36

Views: 12981

Answers (3)

BrokenGlass
BrokenGlass

Reputation: 160912

From MSDN:

public interface ISomeInterface
{
    // ...

    // Indexer declaration:
    string this[int index] { get; set; }
}

Indexers can be declared on an interface (C# Reference). Accessors of interface indexers differ from the accessors of class indexers in the following ways:

  • Interface accessors do not use modifiers.
  • An interface accessor does not have a body.

Upvotes: 16

Albus Dumbledore
Albus Dumbledore

Reputation: 12616

A bit more generic interface (taken from IDictionary<,>), would be:

interface IIndexable<TKey, TValue>
{
    TValue this[TKey key] { get; set; }
}

I only wonder why they didn't include it in mscorlib, so that IDictionary could implement it. It would've made sense.

Upvotes: 3

Esteban Araya
Esteban Araya

Reputation: 29664

Yes, it is possible. In fact, all you're missing is the getter/setter on your indexer. Just add it as follows:

interface IIndexable<T>
{
     T this[string index] {get; set;}
}

Upvotes: 53

Related Questions