0

Class Child implements Parent:

Child : Parent{}

I can add Child object to Parent list.

List<Parent> var = new List<Parent>();

var.Add(new Child());

But how can I add this list of Child into this Dictionary?

Dictionary<string, List<Parent>> var = new Dictionary<string, List<Parent>>();

var.Add("string", new List<Child>());
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
mr_blond
  • 1,586
  • 2
  • 20
  • 52

2 Answers2

0

Well, List<Child> is a completely different type to Child. The fact the generic type used in the List<T> is Child is irrelevant. A Dictionary<string, Child> contains string keys and child objects. Is a List<Child> a child? No. So how would that work?

John
  • 598
  • 2
  • 7
  • 22
0

A List<Child> cannot be assigned to a List<Parent> variable. They are unrelated types. Here's a "proof" by contradiction.

Suppose List<Child> can be assigned to List<Parent>, then this would be allowed by the compiler:

List<Parent> parents = new List<Child>();
parents.Add(new Child2()); // Child2 is another subclass of "Parent"

However, this creates a contradiction. parents actually stores a List<Child>, which is not capable of storing Child2 objects.


A workaround you can use here is to create a List<Parent> object, and add your Child objects into that list:

var.Add("string", new List<Parent>());
List<Child> children = new List<Child> { ... }
var["string"].AddRange(children);
Sweeper
  • 213,210
  • 22
  • 193
  • 313