In C# I have a bunch of objects all inheriting from the same base class.
I also have a number of Dictionaries, one for each subclass.
What I want to do is add all of those Dictionaries to one List so I can loop through them all and do some work (like comparing the lists etc).
In summary
Dictionary<string, Child> childObjects = new Dictionary<string, Child>();
List<Dictionary<string, Parent>> listOfDictionaries = new List<Dictionary<string, Parent>>();
listOfDictionaries.Add(childObjects);
I would have thought that since Child inherits from Parent, this should work, but it won't compile. Clearly I am not understanding something about inheritance and generics :)
A full code example
class Program
{
static void Main(string[] args)
{
//Creating a Dictionary with a child object in it
Dictionary<string, Child> childObjects = new Dictionary<string, Child>();
var child = new Child();
childObjects.Add(child.id, child);
//Creating a "parent" Dictionary with a parent and a child object in it
Dictionary<string, Parent> parentObjects = new Dictionary<string, Parent>();
parentObjects.Add(child.id, child);
var parent = new Parent();
parentObjects.Add(parent.id, parent);
//Adding both dictionaries to a general list
List<Dictionary<string, Parent>> listOfDictionaries = new List<Dictionary<string, Parent>>();
listOfDictionaries.Add(childObjects); //This line won't compile
listOfDictionaries.Add(parentObjects);
}
}
class Parent
{
public string id { get; set; }
public Parent()
{
this.id = "1";
}
}
class Child : Parent
{
public Child()
{
this.id = "2";
}
}
Is there any way of achieving this?