Question

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 ???

Was it helpful?

Solution

You have to specify that both T and K are reference types. Array covariance only works with reference types. Change the declaration to:

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

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 : class as well for clarity.)

OTHER TIPS

type T has to support implicit convertion to K. E.g.

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

has to be valid.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top