6

Why does ICollection<T> implement both IEnumerable<T> and IEnumerable?

What is the purpose of this? How does IEnumerable benefit ICollection<T>?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Maxim Gershkovich
  • 45,951
  • 44
  • 147
  • 243
  • Somewhat similar: [why-does-ienumerablet-inherit-from-ienumerable?](http://stackoverflow.com/questions/221691/why-does-ienumerablet-inherit-from-ienumerable?rq=1) – nawfal Jun 08 '14 at 08:59

3 Answers3

13

IEnumerable<T> itself forces any implementation to also implement the non-generic IEnumerable. This is safe, for the same reasons that IEnumerable<out T> is covariant as of .NET 4... you can always convert the T to object for the non-generic form.

Basically this means that if you've got code which uses a parameter of type IEnumerable, you can still call it with something like List<T>.

Eric Lippert wrote a blog post recently about why collections end up implementing many interfaces, and Brad Abrams wrote a blog post back in 2005 about the specific IEnumerable<T>/IEnumerable decision.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
10

The non-generic interface is for backward compatibility. If you write code using generics and want to pass your collection to some module written in .NET 1.0 (which doesn't have generics) you still want this to succeed, and you want the old method to be able to iterate through it.

Ilya Kogan
  • 21,995
  • 15
  • 85
  • 141
-1

IEnumerable<T> inherits IEnumerable so it makes sense for ICollection<T> to as well. It's just stating explicitly the inheritance that would be there anyway.

Andrew Cooper
  • 32,176
  • 5
  • 81
  • 116