Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

like image 308
Maxim Gershkovich Avatar asked Apr 05 '11 06:04

Maxim Gershkovich


1 Answers

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.

like image 51
Jon Skeet Avatar answered Oct 10 '22 22:10

Jon Skeet