PedroC88
PedroC88

Reputation: 3829

Collections vs. IEnumerable

What are the advantages/disadvantages of inheriting collection vs. implementing iEnumerable()

Upvotes: 4

Views: 1200

Answers (2)

Coding Flow
Coding Flow

Reputation: 21881

Implementing IEnumerable is almost never necessary. There is almost always a suitable collection you can just use.

For me, List<T> and Dictionary<Tkey,TValue> cover 90% of what I usually need to do.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500525

It's usually a mistake (IMO) to derive a class from one of the collection types. I would do it to create a new general purpose collection type - but if the class has some "business" purpose, and just happens to act like a collection in other ways, I think it's not a good idea to derive from a collection class.

If you implement IEnumerable<T> you're effectively giving the message that your class can be used as a sequence of T (probably for a particular, concrete T) but there's more to it than that: it has non-collection abilities too. Of course, you may not even need to implement it yourself - you could have properties or methods which return an appropriate sequence. It depends on the use case, really.

Don't forget that you only get to derive from one base class in .NET... so think very carefully before you use up that one chance on a collection type.

Upvotes: 4

Related Questions