I have a variable of type Func<dynamic> and I am trying to assign it a value. If I assign it to a method that returns a value type (e.g. int), I get the error
'int MethodName()' has the wrong return type
If I wrap the method in a lambda call, however, it works fine. Also methods that return reference types seem to work fine.
private string Test()
{
    return "";
}
private int Test2()
{
    return 0;
}
Func<dynamic> f = Test;           // Works
Func<dynamic> g = Test2;          // Does not
Func<dynamic> h = () => Test2();  // Works
What's wrong with the direct assignment case?
This has nothing to do with dynamic or delegate TResult Func<out TResult>(). You will see the same behavior in this code:
interface I<out T> { }
class C<T> : I<T> { }
...
I<int> a = new C<int>();
I<string> b = new C<string>();
I<object> x = a; // compiler error
I<object> y = b; // no compiler error
For some reason, value types like int will automatically cast to object or dynamic, but I<int> will not automatically cast to I<object> or I<dynamic>. I can't find where in the language reference this is specified.
The reason Func<dynamic> h = () => Test2(); works in your code is because it only requires int to cast to dynamic implicitly, which is fine. It does not require Func<int> to cast to Func<dynamic> implicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With