Reputation: 6296
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
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
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
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