Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I subclass List<T> or have it as a property?

I have faced this problem quite often during the last couple of months, during which I've been building this system. The scenario is this: I have this kind of object that essentially is a list of other objects, but has some other properties specific of its nature. For example:

  • Class Tests:
    • Contains many Test objects
    • Has properties:
      • DefaultTimeouts
      • DefaultNumberOfTries

Should I have this class subclass List<Test> or should I have it inheriting from Object, simply having the list as a property beside the other fields?

I know that this may be a bit subjective and personal taste might play a role here, but I'd wholeheartedly like to know your opinion on this.

like image 482
André Chalella Avatar asked Oct 20 '08 06:10

André Chalella


2 Answers

Contrary to most of the answers here I wouldn't subclass from List in most cases. I found that inheriting from a class to reuse functionality usually causes problems later.

I usually just have a property of type List (or IList) that returns a reference to the list. Usually you only need a get property here. You can control access to the list by choosing to return a readonly version of the list with .AsReadOnly() or just exposing the list as an IEnumerable.

In cases where I want Tests to be a list I usually implement IList and call an internal List field for the actual implementations of the IList. This is a bit more work and results in some more code to maintain but I've found that this is better maintainable than inheriting List just for it's implementation.

like image 184
Mendelt Avatar answered Nov 16 '22 01:11

Mendelt


Sub-class from List<T>. If you have the List generic as a property, it isn't as well encapsulated as a sub-class.

If it looks like a List<T> and it sounds like a List<T>, it probably is a List<T>.

I'd call it a TestCollection.

like image 6
Mark McDonald Avatar answered Nov 16 '22 01:11

Mark McDonald