Converting from Func <object, string> to Func <string, string> works, but Func <int, string> does not work

I have the following code:

static Func<object, string> s_objToString = (x) => x.ToString(); static Func<string, string> s_stringToString = s_objToString; //compiles static Func<int, string> s_intToString = s_objToString; //error 

The second line compiles, but the third line does not compile with an error:

It is not possible to implicitly convert the type ' System.Func<object,string> ' to ' System.Func<int,string> '

Why is this?

I understand that with genetics, although the string is obtained from the object a List<string> not derived from List<object> , but here object to string works and object to int fails, why?

OK, let's say I understand why; Now the question is how to do it (otherwise, than to define the MyInt class in the int field, since Func<object,string> to Func<MyInt,string> )?

+4
source share
2 answers

This is because Func is defined as Func<in T, out TResult> , MSDN here , so T is contravariant with in , that is, you can use either the type you specify, or any type that is not derived, but remember that the match and contradiction does not support value type:

Why covariance and contravariance do not support value type

So, it works for string , but does not work with int . You may need to learn more about covariance and contravariance:

http://msdn.microsoft.com/en-us/library/dd233060.aspx

http://msdn.microsoft.com/en-us/library/dd799517.aspx

+5
source

Since co / contra-variance does not work for value types.

Please look here

Deviation is only supported if the type parameter is a reference type. Difference is not supported for value types.
The following does not compile:

 // int is a value type, so the code doesn't compile. IEnumerable<Object> objects = new List<int>(); // Compiler error here. 
+3
source

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


All Articles