In “Gang of Four”: “Layout Composition over Inheritance,” and this is a great reason for this ...
If we have a SuperClass that looks like this:
public class SuperClass : Person
SuperClass can easily decorate the properties of the Person class by adding properties not found in the Person class. But what happens if the Superclass scenery is for GUI only? For example, a bool value indicates "Selected." We can still get all the Leaders from the database on the List, but we ran into difficulties trying to create a Superclass and combine the results of the database.
foreach( var person in myPersonList){ var sc = new SuperClass(); sc.Selected = false; sc=person; }
The compiler complains because Superclass is not Human for the compiler, it is a Superclass. The only way to populate the properties of the Person subclass is to iterate and set each of them ... like that.
SuperClass.Name = Person.Name; SuperClass.Id = Person.ID;
Pretty tiring. But there is a better way .... Don't make a superclass inherit from Person
public class SuperClass{ public Person ThisPerson {get;set;} public bool Selected {get;set;} }
This gives us "Containment". The superclass now contains the Person class.
Now we can do this:
foreach(var person in MyPersonList){ var sc = new Superclass(); sc.Selected = false; sc.Person = person; }
The consumer of this class should now qualify the properties of the Superclass / Person, like this ...
forach(var sc in MySuperClassList){ var selected = sc.Selected; var name = sc.Person.Name; }
The beauty is that in the future you can add any other container that you want and it will NOT affect other containers. You can also convert the Superclass to everything that it contains. If each of the contained classes becomes an interface, then this is one step further down the road.