a) Compiles
Func<string, bool> f1 = (Func<object, bool>)null;
b) Not
Func<int, bool> f2 = (Func<object, bool>)null;
Why value types are special here? Is contravariance broken with value types?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Generic variance only works with reference types, yes. (This is so that the CLR knows that everything’s still just a reference, so the JITted code is still the same… the bits involved in a reference are the same whatever type you’re talking about, whereas treating
intasobjectrequires a boxing conversion. Basically you can keep representational identity with reference types).From the C# 4 spec, section 13.1.3.2:
It’s the “implicit reference conversion” rather than just “implicit conversion” bit which is a problem for value types.
For much more detail around generic variance, see Eric Lippert’s blog series on the topic.