Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classes with Collections as Properties vs. Classes Inheriting Collections

Recently I used a class that inherits from a collection instead of having the collection instantiated within the class, is this acceptable or does it create unseen problems further down the road? Examples below for the sake of clarity:

public class Cars : List<aCar>

instead of something like:

public class Cars
{
 List<aCar> CarList = new List<aCar>();
}

Any thoughts?

like image 987
wwilkins Avatar asked Dec 08 '08 15:12

wwilkins


2 Answers

The problem with this is that your Cars class will still have the interface it inherits from List, which may allow operations you don't want.

like image 152
Michael Borgwardt Avatar answered Sep 27 '22 20:09

Michael Borgwardt


That depends on the final purpose of your class. If it is only going to work as your own implementation of a collection use inheritance. If not, include a a collection as a property. The second option is more versatile:

  • As you can only inherit from one class, you might need to inherit from another class rather than collection
  • If you need to see this class as a collection you can include an indexer property.
like image 21
Igor Zelaya Avatar answered Sep 27 '22 18:09

Igor Zelaya