List assignment from child to parent

I am trying to do this:

List<Parent> test = new List<Child>(); 

The full code for my class is this:

 class Program { public static void Main(string[] args) { List<Parent> test = new List<Child>(); test.Add(new Child()); test.Add(new AnotherChild()); } } class Parent { } class Child : Parent { } class AnotherChild : Parent { } 

Can someone please explain to me why this gives me this error:

Error 2: Cannot convert the type "System.Collections.Generic.List" to "System.Collections.Generic.List" d: \ personal \ documents \ visual studio 2010 \ Projects \ ConsoleApplication3 \ ConsoleApplication3 \ Program.cs 20 24 ConsoleApplication3

And why does it work?

 Parent[] test = new Child[10]; List<Parent> result = test.ToList(); 

Thanks:)

- On right:

Now I know why: List is compiled into List`1 and List to List`2 . And they have no relationship.

+4
source share
5 answers

Update: because the two types List<Parent> and List<Child> are not a co-option .

Despite the fact that the general parameter that you pass, Child , inherits from Parent , the connection is not transferred to private list types. Thus, the resulting two types of list are not interchangeable.

.Net 4.0 introduces codimension / contradiction. Your code will still not work with .Net 4.0, since none of the List or IList classes will be modified to be a co-option.

+6
source

You cannot do this because List<Child> not assigned to List<Parent> , although Child assigned to Parent . The type List<T> is invariant.

Is there a reason why you cannot use something like this?

 public static void Main(string[] args) { List<Parent> test = new List<Parent>(); test.Add(new Child()); test.Add(new AnotherChild()); } 
+3
source

Use this

  List<Parent> test = new List<Child>().Cast<Parent>().ToList(); 
+1
source

Generalizations in C # are invariant, that is, there is no subtype relationship between different instances of the generic type.

Conceptually speaking, List<Child> cannot be a subtype of List<Parent> , because you can insert an instance of AnotherChild in List<Parent> , but not in List<Child> .

+1
source

I advise you this figure (it has a good description of covariance and contravariance.): Http://blog.tlk.com/dot-net/2009/c-sharp-4-covariance-and-contravariance

0
source

Source: https://habr.com/ru/post/1303397/


All Articles