views:

262

answers:

2

Hi,

I am trying to develop a Silverlight 4 application using C# 4.0. I have a case like this:

public class Foo<T> : IEnumerable<T>
{
    ....
}

Elsewhere:

public class MyBaseType : MyInterface
{
    ...
}

And the usage where I am having problems:

Foo<MyBaseType> aBunchOfStuff = new Foo<MyBaseType>();
Foo<MyInterface> moreGeneralStuff = myListOFStuff;

Now I believe this was impossible in C# 3.0 because generic type were "Invariant". However I thought this was possible in C# 4.0 through the new covariance for generics technology?

As I understand it, in C# 4.0 a lot of common interfaces (like IEnumerable) have been modified to support variance. In this case does my Foo class need to anything special in order to become covariant?

And is covariance supported in Silverlight 4 (RC) ?

+1  A: 

Covariance is only supported for Interfaces and Delegates:

public interface Foo<out T> { }
public class Bar<T> : Foo<T> { }

interface MyInterface { }
public class MyBase : MyInterface { }

Foo<MyBase> a = new Bar<MyBase>();
Foo<MyInterface> b = a;

Important is the out-Keyword on the Interface Foo.

gammelgul
Thanks, I see the mistake I made with the interface...
Ant
+1  A: 

To indicate that the generic type parameter of an interface or delegate is covariant in T, you need to supply the out keyword.

However this is currently not possible for classes. I suggest to create an interface with a covariant generic type parameter, and let your class implement it.

As for covariance support in Silverlight 4: In the beta's it wasn't supported, I would need to check if they have implemented it in the release candidate. Edit: Apparently it is.

Yannick M.
thanks, useful answer
Ant