I know that C# supports covariance in arrays like this :
object[] array = new string[3];
But I’m getting an error when it tries to compile the below code
class Dummy<K,T> where T:K { public void foo() { K[] arr = new T[4]; } }
It says ‘Cannot implicitly convert type ‘T[]’ to ‘K[]’ ‘
Why I’m getting this error ???
You have to specify that both T and K are reference types. Array covariance only works with reference types. Change the declaration to:
and it works fine. You don’t have to specify that K is a reference type, because if T is a reference type and it derives from or implements K, then K must be a reference type too. (At least I assume that’s the reasoning. It doesn’t hurt to add
where K : classas well for clarity.)