#1,146 – Generics Don’t Support Covariance

In C#, arrays are covariant, so you can do the following:

            // Array covariance--OK
            Dog[] dogs = new Terrier[5];

Generics in C#, however, are not covariant (they are invariant). The following code will not compile.

            // Generic covariance--not OK (compiler error)
            List<Dog> moreDogs = new List<Terrier>();

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

6 Responses to #1,146 – Generics Don’t Support Covariance

  1. Pingback: Dew Drop – July 25, 2014 (#1822) | Morning Dew

  2. Joseph says:

    Actually, not true. Generics in C# can be both covariant and contravariant. See http://msdn.microsoft.com/en-us/library/dd799517.aspx.

  3. Joseph says:

    To clarify, List is invariant, but that’s because the type must go both directions. In a read only collection or IEnumerable or Action or Func, the generic type may be covariant or contravariant.

  4. vikram says:

    class cls
    {
    }

    list lstcls = new list();
    cls[] arrcls = new cls[10];

    what is the diff of list class and array class?

Leave a comment