Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading