Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define Indexer behaviour to an Interface?

Tags:

c#

interface

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

something like this :

interface IIndexable<T> {    T this[string index]; } 
like image 831
Christophe Debove Avatar asked Mar 06 '12 15:03

Christophe Debove


People also ask

Can an interface have indexers?

Indexers can be declared on an interface. Accessors of interface indexers differ from the accessors of class indexers in the following ways: Interface accessors do not use modifiers. An interface accessor typically does not have a body.

CAN interface have indexers like class?

In C#, an interface can be defined using the interface keyword. An interface can contain declarations of methods, properties, indexers, and events. However, it cannot contain fields, auto-implemented properties.

Can an interface contain the signature of an indexer?

An interface cannot contain the signature of an indexer. Interfaces members are automatically public. To implement an interface member, the corresponding member in the class must be public as well as static.

What is the correct syntax for declaring the indexer?

private T[] arr = new T[100]; // Define the indexer to allow client code to use [] notation. public T this[int i] { get => arr[i]; set => arr[i] = value; } } class Program { static void Main() { var stringCollection = new SampleCollection<string>(); stringCollection[0] = "Hello, World."; Console.


1 Answers

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;} } 
like image 126
Esteban Araya Avatar answered Sep 29 '22 03:09

Esteban Araya