c# - Why not inherit from List<T>?

ID : 698

viewed : 299

Tags : c#.netlistoopinheritancec#

Top 5 Answer for c# - Why not inherit from List<T>?

vote vote


There are some good answers here. I would add to them the following points.

What is the correct C# way of representing a data structure, which, "logically" (that is to say, "to the human mind") is just a list of things with a few bells and whistles?

Ask any ten non-computer-programmer people who are familiar with the existence of football to fill in the blank:

A football team is a particular kind of _____

Did anyone say "list of football players with a few bells and whistles", or did they all say "sports team" or "club" or "organization"? Your notion that a football team is a particular kind of list of players is in your human mind and your human mind alone.

List<T> is a mechanism. Football team is a business object -- that is, an object that represents some concept that is in the business domain of the program. Don't mix those! A football team is a kind of team; it has a roster, a roster is a list of players. A roster is not a particular kind of list of players. A roster is a list of players. So make a property called Roster that is a List<Player>. And make it ReadOnlyList<Player> while you're at it, unless you believe that everyone who knows about a football team gets to delete players from the roster.

Is inheriting from List<T> always unacceptable?

Unacceptable to who? Me? No.

When is it acceptable?

When you're building a mechanism that extends the List<T> mechanism.

What must a programmer consider, when deciding whether to inherit from List<T> or not?

Am I building a mechanism or a business object?

But that's a lot of code! What do I get for all that work?

You spent more time typing up your question that it would have taken you to write forwarding methods for the relevant members of List<T> fifty times over. You're clearly not afraid of verbosity, and we are talking about a very small amount of code here; this is a few minutes work.


I gave it some more thought and there is another reason to not model a football team as a list of players. In fact it might be a bad idea to model a football team as having a list of players too. The problem with a team as/having a list of players is that what you've got is a snapshot of the team at a moment in time. I don't know what your business case is for this class, but if I had a class that represented a football team I would want to ask it questions like "how many Seahawks players missed games due to injury between 2003 and 2013?" or "What Denver player who previously played for another team had the largest year-over-year increase in yards ran?" or "Did the Piggers go all the way this year?"

That is, a football team seems to me to be well modeled as a collection of historical facts such as when a player was recruited, injured, retired, etc. Obviously the current player roster is an important fact that should probably be front-and-center, but there may be other interesting things you want to do with this object that require a more historical perspective.

vote vote


Wow, your post has an entire slew of questions and points. Most of the reasoning you get from Microsoft is exactly on point. Let's start with everything about List<T>

  • List<T> is highly optimized. Its main usage is to be used as a private member of an object.
  • Microsoft did not seal it because sometimes you might want to create a class that has a friendlier name: class MyList<T, TX> : List<CustomObject<T, Something<TX>> { ... }. Now it's as easy as doing var list = new MyList<int, string>();.
  • CA1002: Do not expose generic lists: Basically, even if you plan to use this app as the sole developer, it's worthwhile to develop with good coding practices, so they become instilled into you and second nature. You are still allowed to expose the list as an IList<T> if you need any consumer to have an indexed list. This lets you change the implementation within a class later on.
  • Microsoft made Collection<T> very generic because it is a generic concept... the name says it all; it is just a collection. There are more precise versions such as SortedCollection<T>, ObservableCollection<T>, ReadOnlyCollection<T>, etc. each of which implement IList<T> but not List<T>.
  • Collection<T> allows for members (i.e. Add, Remove, etc.) to be overridden because they are virtual. List<T> does not.
  • The last part of your question is spot on. A Football team is more than just a list of players, so it should be a class that contains that list of players. Think Composition vs Inheritance. A Football team has a list of players (a roster), it isn't a list of players.

If I were writing this code, the class would probably look something like so:

public class FootballTeam<T>//generic class {     // Football team rosters are generally 53 total players.     private readonly List<T> _roster = new List<T>(53);      public IList<T> Roster     {         get { return _roster; }     }      // Yes. I used LINQ here. This is so I don't have to worry about     // _roster.Length vs _roster.Count vs anything else.     public int PlayerCount     {         get { return _roster.Count(); }     }      // Any additional members you want to expose/wrap. } 
vote vote


class FootballTeam : List<FootballPlayer>  {      public string TeamName;      public int RunningTotal; } 

Previous code means: a bunch of guys from the street playing football, and they happen to have a name. Something like:

People playing football

Anyway, this code (from m-y's answer)

public class FootballTeam {     // A team's name     public string TeamName;       // Football team rosters are generally 53 total players.     private readonly List<T> _roster = new List<T>(53);      public IList<T> Roster     {         get { return _roster; }     }      public int PlayerCount     {         get { return _roster.Count(); }     }      // Any additional members you want to expose/wrap. } 

Means: this is a football team which has management, players, admins, etc. Something like:

Image showing members (and other attributes) of the Manchester United team

This is how is your logic presented in pictures…

vote vote


This is a classic example of composition vs inheritance.

In this specific case:

Is the team a list of players with added behavior


Is the team an object of its own that happens to contain a list of players.

By extending List you are limiting yourself in a number of ways:

  1. You cannot restrict access (for example, stopping people changing the roster). You get all the List methods whether you need/want them all or not.

  2. What happens if you want to have lists of other things as well. For example, teams have coaches, managers, fans, equipment, etc. Some of those might well be lists in their own right.

  3. You limit your options for inheritance. For example you might want to create a generic Team object, and then have BaseballTeam, FootballTeam, etc. that inherit from that. To inherit from List you need to do the inheritance from Team, but that then means that all the various types of team are forced to have the same implementation of that roster.

Composition - including an object giving the behavior you want inside your object.

Inheritance - your object becomes an instance of the object that has the behavior you want.

Both have their uses, but this is a clear case where composition is preferable.

vote vote


As everyone has pointed out, a team of players is not a list of players. This mistake is made by many people everywhere, perhaps at various levels of expertise. Often the problem is subtle and occasionally very gross, as in this case. Such designs are bad because these violate the Liskov Substitution Principle. The internet has many good articles explaining this concept e.g., http://en.wikipedia.org/wiki/Liskov_substitution_principle

In summary, there are two rules to be preserved in a Parent/Child relationship among classes:

  • a Child should require no characteristic less than what completely defines the Parent.
  • a Parent should require no characteristic in addition to what completely defines the Child.

In other words, a Parent is a necessary definition of a child, and a child is a sufficient definition of a Parent.

Here is a way to think through ones solution and apply the above principle that should help one avoid such a mistake. One should test ones hypothesis by verifying if all the operations of a parent class are valid for the derived class both structurally and semantically.

  • Is a football team a list of football players? ( Do all properties of a list apply to a team in the same meaning)
    • Is a team a collection of homogenous entities? Yes, team is a collection of Players
    • Is the order of inclusion of players descriptive of the state of the team and does the team ensure that the sequence is preserved unless explicitly changed? No, and No
    • Are players expected to be included/dropped based on their sequencial position in the team? No

As you see, only the first characteristic of a list is applicable to a team. Hence a team is not a list. A list would be a implementation detail of how you manage your team, so it should only be used to store the player objects and be manipulated with methods of Team class.

At this point I'd like to remark that a Team class should, in my opinion, not even be implemented using a List; it should be implemented using a Set data structure (HashSet, for example) in most cases.

Top 3 video Explaining c# - Why not inherit from List<T>?