views:

444

answers:

3

Hi,

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

A: 

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

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

has to be valid.

Fredrik Jansson
The implicit conversion side is specified by the T:K part. See my answer for what's missing.
Jon Skeet
+7  A: 

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.)

Jon Skeet
A: 

Bart De Smet has a great blog entry about covariance & contravariance here.

Mike Thompson