C # 4.0 RC, Silverlight 4.0 RC Covariance

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> { .... } 

In the other place:

 public class MyBaseType : MyInterface { ... } 

And use where problems arise:

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

Now I believe that this is not possible in C # 3.0 because the generic type was "Invariant". However, I thought it was possible in C # 4.0 thanks to the new covariance for generic technology?

As I understand it, several common interfaces (like IEnumerable) were created in C # 4.0 to support dispersion. In this case, does the Foo class need something special to become covariant?

And covariance is supported in Silverlight 4 (RC)?

0
source share
2 answers

Covariance is supported only 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; 

The important thing is out -Keyword on the Foo interface.

+1
source

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

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

As for support for covariance in Silverlight 4: it was not supported in beta, I needed to check if they implemented it in a candidate for release. Edit: Apparently this is so.

Edit2: There can be some confusion as to whether SL4 supports joint and contravariance for interfaces and delegates due to the fact that some of the types in BCL do not have corresponding type modifiers ( IEnumerable<T> , Action<T> , Func<T> , ...).

Silverlight 5 solves these problems: http://10rem.net/blog/2011/09/04/the-big-list-of-whats-new-or-improved-in-silverlight-5

However, the SL4 compiler does support in and out modifiers. The following compiles and works as expected:

 interface IFoo<out T> { T Bar { get; } } interface IBar<in T> { void Add(T value); } delegate void ContravariantAction<in T>(T value); delegate T CovariantFunc<out T>(); 
+4
source

Source: https://habr.com/ru/post/922771/


All Articles