2

I know exactly the same question appears here on StackOverflow, nevertheless it does not quite answer my query.

If ICollection<T> implements IEnumerable<T>, which extends IEnumerable, why did programmers from Microsoft add IEnumerable as an interface that the ICollection<T> implements?

Isn't it exactly (semantically and implementation wise) the same as simply writing ICollection<T> : IEnumerable<T>?

Orkun
  • 6,998
  • 8
  • 56
  • 103
Bober02
  • 15,034
  • 31
  • 92
  • 178

1 Answers1

5

It says it implements IEnumerable because it implements IEnumerable.

IEnumerable<T> inherits IEnumerable, but it can obviously provide no implementation. Classes that implement IEnumerable<T> must also implement IEnumerable, whether or not they explicitly state that they do so.

class Foo : IEnumerable<T> 
class Foo : IEnumerable<T>, IEnumerable

With either case, you implement the members of both interfaces. The second class definition simply makes it obvious for those looking at the class and/or the documentation, which is a good thing. An inexperienced or otherwise uninformed reader might not know that IEnumerable<T> brings IEnumerable along with it. They might might not know that a class that implements IEnumerable<T> can be used where an IEnumerable is expected. This simply provides a bit more information to the reader, which can only be a good thing on average.

Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
  • 2
    And tools like IlDasm and Reflector tend to show the 2nd longer form. Regardless from how it was written. – H H Feb 17 '12 at 18:55
  • OK, so it is for readability rather than to provide any semantic/programming difference, is that correct? – Bober02 Feb 17 '12 at 19:18
  • Pretty much. It's optional to *list* the additional interfaces that are brought along. Implementations thereof are required either way. – Anthony Pegram Feb 17 '12 at 19:34
  • @Bober02, Eric Lippert did a [nice write-up](http://blogs.msdn.com/b/ericlippert/archive/2011/04/04/so-many-interfaces.aspx) in his blog based on a [similar question](http://stackoverflow.com/questions/4817369/why-does-does-it-really-listt-implement-all-these-interfaces-not-just-ilis). – Anthony Pegram Feb 17 '12 at 19:38