Why C# Func<int> cannot be assigned to Func<object>?

97 views Asked by At

I've studied Covariant and Contravariant in C#. and below my code has an error.

object a = new object();
int b = 10;

a = b; // not error


Func<object> acO = () => new object();
Func<int> acI = () => 1;

acO = acI; // error

Error Message:

Cannot implicitly convert type 'System.Func' to type 'System.Func'.

I thought that if int -> object is possible, Func -> Func will be possible. but it is not.

I think value type will be copied to use when it is returned unlike reference type(object) and it can cause unintentional operation(like exception). Is my guess correct?

I'm looking forward to your wise answers. Thank you for reading.

1

There are 1 answers

2
Guru Stron On BEST ANSWER

From the Variance in Delegates (C#) docs:

Variance for generic type parameters is supported for reference types only.

A nice blog post diving into the topic by Eric Lippert:

All the built-in reference conversions are identity-preserving. This is why covariant and contravariant conversions of interface and delegate types require that all varying type arguments be of reference types. To ensure that a variant reference conversion is always identity-preserving, all of the conversions involving type arguments must also be identity-preserving. The easiest way to ensure that all the non-trivial conversions on type arguments are identity-preserving is to restrict them to be reference conversions.