Expression.Convert usually throws an InvalidOperationException when "the expression operator is not defined between the expression. Type and type."
The return type parameter Func<> is covariant for reference types.
// This works. Func<SomeType> a = () => new SomeType(); Func<object> b = a;
It is not covariant for value types .
Deviation applies only to reference types; if you specify a value type for a variant type parameter, this parameter type is invariant for the resulting constructed type.
However, Expression.Convert believes this is possible.
Func<int> answer = () => 42; Expression answerExpression = Expression.Constant( answer ); // No InvalidOperationException is thrown at this line. Expression converted = Expression.Convert( answerExpression, typeof( Func<object> ) );
No InvalidOperationException is InvalidOperationException when Expression.Convert called. The expression tree compiles correctly, but when I call the created delegate, I get the expected InvalidCastException .
It seems that all rejection logic is not properly supported. He correctly complains about the impossibility of converting from Func<SomeType> to Func<SomeOtherType> , but he does not complain about converting from Func<object> to Func<string> .
Interestingly, once SomeType and SomeOtherType are in the same class hierarchy ( SomeOtherType continues from SomeType ), it never throws an exception. If this is not so, then.
source share