Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 182 ยท Collections

IEnumerable, ICollection and IList

Understand the C# collection interface hierarchy - IEnumerable, ICollection, IList - how foreach and IEnumerator work by hand, yield return, custom collections and covariance.

You have met arrays, lists, sets, dictionaries and queues. Behind all of them sits a small family of interfaces that describe what a collection can do: IEnumerable<T> ("you can walk through me"), ICollection<T> ("I also have a size and can be added to"), IList<T> ("I am also indexed by position"). Every foreach loop, every LINQ query and every method that says "give me some items" is written against these interfaces rather than against List<T> or T[].

Understanding them pays off three times. You write methods that accept the widest useful input. You can build your own collections that work with foreach and LINQ. And you can finally see what foreach really does, by writing an enumerator by hand. This lesson walks through the hierarchy, the rule of thumb "accept the narrowest interface, return the one you can promise", IEnumerator<T>, yield return, a custom collection and covariance.

The hierarchy

The generic interfaces build on each other. Each layer adds abilities:

Interface Adds Typical members
IEnumerable<T> iterate forward once GetEnumerator()
IReadOnlyCollection<T> a known size Count
IReadOnlyList<T> access by index this[int]
ICollection<T> size, change, test Count, Add, Remove, Contains, Clear, CopyTo, IsReadOnly
IList<T> indexed read and write this[int], Insert, RemoveAt, IndexOf

List<T> implements all of them. An array T[] implements IList<T> too (although Add throws NotSupportedException because an array has a fixed size). HashSet<T> is an ICollection<T> but not an IList<T>, since a set has no positions. A LINQ query result is only an IEnumerable<T>.

C# One list, many interface views

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

All four variables point at one object. The interface you choose decides which members the compiler lets you call. That is the idea of programming to an interface.

Choosing parameter and return types

A useful guideline:

  • Parameters: accept the narrowest interface that does the job. If you only loop over the items, accept IEnumerable<T>. If you also need Count without enumerating, accept IReadOnlyCollection<T>. If you need an index, IReadOnlyList<T>. Callers can then pass arrays, lists, sets, LINQ queries or collection expressions.
  • Return types: return something precise that you can promise. IReadOnlyList<T> for a fixed result, List<T> or T[] for a result the caller owns and may edit. Avoid returning IEnumerable<T> when you already have a list, because the caller cannot tell whether it is already materialized.
C# Accepting the widest input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Because the method only walks forward, any sequence will do. Accepting List<int> would have forced callers to convert a set, a range or a queue first.

An IEnumerable<T> may be a deferred LINQ query that re-runs every time you enumerate it. Looping over it twice runs the query twice, which is wasteful or even wrong if the source has side effects. When you need the data more than once, call ToList() or ToArray() once and reuse the result.

What foreach really does

A foreach loop is shorthand for calling GetEnumerator() and then repeating MoveNext() and Current until MoveNext() returns false. The enumerator type is IEnumerator<T>, with exactly three members: MoveNext(), Current and Dispose(). Here is a loop and its hand-written equivalent:

C# foreach unrolled by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The enumerator remembers where it is, so each foreach gets its own independent position. Dispose is called at the end, which matters for enumerators that hold files, locks or database cursors.

The compiler does not insist on the interfaces: foreach works on any type with a public GetEnumerator() method that returns something with MoveNext() and Current (the "duck typing" pattern). List<T> uses this to return a struct enumerator and avoid an allocation. The interfaces matter when you need to pass collections around as a general type.

Writing an enumerator yourself

To see how little there is to it, here is a small class that counts down, with the enumerator written out explicitly:

C# A hand-written IEnumerable and IEnumerator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

IEnumerable<T> forces you to implement two GetEnumerator methods: the generic one, and the old non-generic one from the pre-generics IEnumerable, which can simply forward to the generic version. The same goes for Current. The class gets full LINQ support (Sum, Where, ToList, ...) just by implementing this interface.

yield return: let the compiler write the enumerator

That was a lot of code for a countdown. C# has a shortcut: a method that returns IEnumerable<T> and contains yield return is turned by the compiler into a state machine class very much like the one above. You write a loop; the compiler writes the bookkeeping. More on this in Iterators and yield.

C# The same countdown with yield return

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two things to observe. The body of Evens does not start running when you call it, only when the first item is requested, so "Created the sequence." prints before "(starting Evens)". And Evens describes an infinite sequence, which is fine because Take(3) stops asking after three items. This lazy evaluation is the foundation of LINQ.

Implementing ICollection and IList

Implementing IEnumerable<T> gives you read-only, forward-only access. If your collection should also support Add, Remove and indexing, you need ICollection<T> or IList<T>. That is a lot of members, so a common shortcut is to wrap a List<T> or inherit from Collection<T> (in System.Collections.ObjectModel), which implements IList<T> and exposes virtual hooks such as InsertItem and RemoveItem.

C# Collection of T with validation hooks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Every way of adding (Add, Insert, the indexer) goes through InsertItem, so one override covers them all. This is why you should inherit from Collection<T> instead of from List<T>: List<T>'s methods are not virtual, so a subclass cannot intercept them.

Covariance: IEnumerable

Suppose Dog inherits from Animal. Is a list of dogs a list of animals? The answer depends on whether the interface only reads items or also writes them.

IEnumerable<out T> and IReadOnlyList<out T> are covariant, declared with the out keyword. They only hand items out, so a sequence of Dog can safely be used wherever a sequence of Animal is expected. IList<T> and ICollection<T> are invariant, because they accept items as well (Add(T)), and allowing the conversion would let you add a Cat to a list that really holds dogs.

C# Covariance with IEnumerable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Arrays are also covariant, but for historical reasons they check at runtime, which makes them unsafe:

C# Array covariance fails at run time (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler accepts this, but the second assignment throws System.ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array. because the real array can only hold Dog objects. Generic interfaces avoid the trap by making only the safe direction covariant. See Covariance and Contravariance for the full story, and Arrays for the array side.

Practical advice

  • Prefer IEnumerable<T> for inputs you only loop over, and IReadOnlyList<T> or IReadOnlyCollection<T> when you need Count or an index.
  • Do not use the non-generic IEnumerable, ICollection and IList in new code, except where you must implement them next to the generic versions.
  • Do not cast an IEnumerable<T> to List<T> and mutate it; you have no promise about what is behind the interface.
  • Calling Count() on an IEnumerable<T> may have to enumerate everything. LINQ checks whether the source is an ICollection<T> and uses its Count property if it can; TryGetNonEnumeratedCount exposes that check.
  • Multiple enumeration of a lazy sequence is a common performance bug. Materialize once with ToList().

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which interface adds access by index and Insert/RemoveAt on top of ICollection<T>?

    IList<T> extends ICollection<T> with the indexer, Insert, RemoveAt and IndexOf.
  2. 2. What are the members of IEnumerator<T> that foreach uses?

    foreach calls GetEnumerator, then MoveNext repeatedly and reads Current, and finally disposes the enumerator.
  3. 3. Why does a method with yield return not run any of its body when you call it?

    The compiler turns the method into a state machine. Code runs up to each yield return only when the consumer asks for the next item.
  4. 4. Why is IEnumerable<Animal> animals = new List<Dog>(); allowed but IList<Animal> animals = new List<Dog>(); not?

    If IList<Animal> could point to a list of dogs, you could Add a Cat to it. Covariance is only safe for read-only access.
  5. 5. You write a method that only loops over its input once. Which parameter type is the best choice?

    The narrowest interface that does the job accepts arrays, lists, sets, queries and collection expressions.

Summary

  • IEnumerable<T> means "can be iterated"; ICollection<T> adds a size and Add/Remove/Contains; IList<T> adds position-based access.
  • Accept the narrowest interface for parameters; return a type that tells the caller what they may do.
  • foreach calls GetEnumerator(), then MoveNext() and Current, and disposes the enumerator.
  • yield return makes the compiler build the enumerator state machine; sequences are lazy and can be infinite.
  • To customize a list-like collection, inherit Collection<T> and override InsertItem/RemoveItem, not List<T>.
  • IEnumerable<out T> and IReadOnlyList<out T> are covariant; IList<T> is invariant; arrays are covariant but check types at run time.
  • Beware of enumerating a lazy IEnumerable<T> more than once.

Next: Choosing the Right Collection