C # -Array covariance in common classes

I know that C # supports covariance in arrays as follows:

object[] array = new string[3]; 

But I get an error when trying to compile the code below

 class Dummy<K,T> where T:K { public void foo() { K[] arr = new T[4]; } } 

It says: "It is not possible to implicitly convert the type" T [] "to" K [] ""

Why am I getting this error ???

+6
generics c # covariance
source share
2 answers

You must indicate that both T and K are reference types. Array covariance only works with reference types. Change the announcement to:

 class Dummy<K,T> where T : class, K 

and it works great. You do not need to indicate that K is a reference type, because if T is a reference type, and it comes from or implements K, then K must also be a reference type. (At least I assume the reasoning. This will not hurt to add where K : class , as well as for clarity.)

+12
source share

type T must support implicit conversion to K. For example:

T a = new T (); K b = a;

must be valid.

-one
source share

All Articles