Why don't covariant type parameters allow me to write [List <object> lst = new List <string> ()]?

If the Covariant parameters that are added in .Net Framework 4 allow me to make assignments that look like polymorphism

Why can I write

IEnumerable<object> lst = new List<string>();

And I can not write

List<object> lst = new List<string>();
+3
source share
2 answers

There are two reasons why this does not work:

  • IEnumerable<T>is covariant (declared public interface IEnumerable<out T>), but IList<T>not. Otherwise, you can do something like this:

    IList<string> listOfStrings = ...
    IList<object> listOfObjects = listOfStrings;
    listOfObjects.Add(42); // would fail at runtime because it is actually a list of strings, not ints
    
  • Covariance and contravariance only work on interfaces, not specific classes.

From MSDN :

.NET Framework 4 .

+4

List {T} , :

List<object> lst = new List<string>();
lst.Add(10);

, Int32 .

IEnumerable {out T} , 'out'. , , , .

, , :

List<object> lst = new List<object>();
lst.AddRange(new string[] { "hello" });
+2

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


All Articles