Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexable interface

Tags:

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.

like image 940
Brian Triplett Avatar asked Jun 29 '10 14:06

Brian Triplett


1 Answers

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 indexer
  • IReadOnlyCollection<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[]
like image 182
Meirion Hughes Avatar answered Oct 20 '22 23:10

Meirion Hughes