#1,146 – Generics Don’t Support Covariance
July 25, 2014 6 Comments
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>();
Pingback: Dew Drop – July 25, 2014 (#1822) | Morning Dew
Actually, not true. Generics in C# can be both covariant and contravariant. See http://msdn.microsoft.com/en-us/library/dd799517.aspx.
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.
(See http://blogs.msdn.com/b/ericlippert/archive/2007/10/17/covariance-and-contravariance-in-c-part-two-array-covariance.aspx)
For more details, see the MSDN documentation: http://msdn.microsoft.com/en-us/library/dd799517.aspx
class cls
{
}
list lstcls = new list();
cls[] arrcls = new cls[10];
what is the diff of list class and array class?