Bober02
Bober02

Reputation: 15341

Collection<T>: why does it implement both IEnumerable and IEnumerable<T>?

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>?

Upvotes: 2

Views: 218

Answers (1)

Anthony Pegram
Anthony Pegram

Reputation: 126834

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.

Upvotes: 5

Related Questions