I have base class that is called Entity.
Then I have two child class Tag, and Property that inherits from Entity.
Now I want to have dictionary that stores a List of Entity. But I cannot get it to work. Have a done the inheritance wrongly?
Dictionary<string, List<Entity>> baseDict = new Dictionary<string, List<Entity>>();
List<Tag> tags = new List<Tag>();
tags.Add(new Tag("2012"));
tags.Add(new Tag("hello"));
tags.Add(new Tag("lego"));
List<Properties> properties = new List<Properties>();
properties.Add(new Properties("Year"));
properties.Add(new Properties("Phrase"));
properties.Add(new Properties("Type"));
baseDict.Add("Tags", tags);
baseDict.Add("Properties", properties);
This is a common mistake.
A
List<Derived>does not automatically inherit from aList<Base>, and they cannot be used interchangeably. The reason for this is that a list is a mutable structure, i.e. elements can be added, removed, and modified.For example, if I have a
List<Dog>and aList<Cat>lists, and I was able to treat them as aList<Mammal>, then the following code will be possible:However, if you do not need lists, just collections, (and you use C# 4 or later), you could define the dictionary as
Dictionary<string, IEnumerable<Entity>>. WIth anIEnumerableit is not possible to add or modify the collection, just enumerate it, so any funny bussiness is by definition dissalowed. This is called Generic Type Covariance, and if you would like to read more on the subject, there are several great Eric Lippert blogs.