tags:

views:

53

answers:

3

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.

+4  A: 

IList<> (assuming you want to stay generic) is the only interface to include an indexer.

However, you can just explicitly implement and throw NotSupportedException for all those operations you don't want to support, or just implement IEnumerable<> and have the rest on the class only, not in an interface.

Lucero
A: 

Why not just IEnumerable<> + a custom interface with just an indexer?

Mau
A: 

You can expose it as IEnumerable<T> and still have indexing behavior via LINQ .ElementAt and .Count. If the underlying collection supports IList<T>, these are still O(1) operations as LINQ is smart enough to optimize for list implementations. Granted, .ElementAt is not as succinct as an indexer, but it also gives you flexibility if the underlying implementation changes to a collection that doesn't directly support indexing. If you don't want to use this approach, it's not too difficult to create a wrapper class that implements a read-only indexer and delegates all calls to an underlying list.

Dan Bryant