Is it possible to add the indexer behaviour from an interface?
something like this :
interface IIndexable<T> { T this[string index]; }
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.
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.
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.
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.
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;} }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With