Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't assign methods that return value types to Func<dynamic> [duplicate]

Tags:

c#

dynamic

func

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?

like image 204
Kris Harper Avatar asked Nov 05 '15 19:11

Kris Harper


1 Answers

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.

like image 102
Timothy Shields Avatar answered Oct 11 '22 23:10

Timothy Shields