There is the following not a big project:

AbstractClass.cs

public abstract class AbstractClass { } 

Gover.cs

 class Gover : AbstractClass { } 

Program.cs

 class Program { public List<AbstractClass> list; void Main(string[] args) { list = new List<Gover>(); //Ошибка: Неявное преобразование типа "...List<abstrac.Gover>" в "...List<abstrac.AbstractClass> } 

But an error appears (as shown above) that is not clear to me. Why can't I assign a Gover object to the AbstractClass object? After all, Gover inherited from AbstractClass?

    2 answers 2

    As @VladD already said, the problem is that List<T> not covariant with respect to T (since List<T> is a class, and classes in C # can only be invariant). However, instead, you can use the covariant IEnumerable<T> interface it implements to make your code work. For example:

     public class Test { public static IEnumerable<AbstractClass> list; static void Main(string[] args) { list = new List<Gover>(); } } 

      The problem is this: List<T> not covariant with T Normal words: If T1 is a subclass of T2 , then List<T1> not a subclass of List<T2> .

      Why is this so? See it. Suppose that, as you wrote, it would be possible:

       public List<AbstractClass> list; List<Gover> goverList = new List<Gover>(); list = goverList; 

      Then it would be possible to write:

       list.Add(new Gover2()); 

      where Gover2 is another descendant of AbstractClass . That is, in the goverList list, which seems to be of type List<Gover> , suddenly there would be an element of a foreign type, Gover2 . Catastrophe!


      Conclusion: the way you wrote, will not work. Write list = new List<Gover>() , for example. Or make the list type a template. Or something else, depending on what you need.

      • Oh you! Really. Thanks @VladD. - Adam
      • @derkode: Please! - VladD