tags:

views:

39

answers:

2

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

+1  A: 

Implementing IEnumerable is almost never necesary, there is slmost always a suitable collection you can just use. List<T> and Dictionary<Tkey,TValue> cover 90% of what i usually need to do.

Ben Robinson
Just like you do, Inheritance covers almost everything I do (noting that I come from .NET 1.1 programming).But I had the idea that implementing iEnumerable<T> would give me more control of my class. So i really wanted to ask :)
pedro_cesar
I have never felt the need to extend a collection class by inheriting from it, i just find that the built in .net class library collections do 99.9% of the things i would ever need to do. In that 0.01% case i would probably implement IEnumerable
Ben Robinson
+2  A: 

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.

Jon Skeet