What C# interface should be used if I only want to be able to index into instances of a type? I don't need (or want) the ability to add/remove/edit elements. Enumeration is okay. Does this require a custom IIndexable
type?
In this case IList
is overkill because it forces implementation of members I don't want to have.
As of .Net 4.5 the (arguably) right way is now to use IReadOnlyList<T>
, which derives from IReadOnlyCollection<T>
, which derives from IEnumerable<T>
IReadOnlyList<T>
gives you the indexerIReadOnlyCollection<T>
gives you the collection Count property. IEnumerable<T>
gives you the collection Enumerator. Its about as light as you can make it.
Core classes that directly implement IReadOnlyList
:
List<T>
Collection<T>
ReadOnlyCollection<T>
ArraySegment<T>
T[]
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