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:
Tests
:
Test
objectsDefaultTimeouts
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With