How to return value with anonymous method?

This fails

string temp = () => {return "test";};

with the error

Cannot convert lambda expression to type 'string' because it is not a delegate type

What does the error mean and how can I resolve it?


Solution 1:

The problem here is that you've defined an anonymous method which returns a string but are trying to assign it directly to a string. It's an expression which when invoked produces a string it's not directly a string. It needs to be assigned to a compatible delegate type. In this case the easiest choice is Func<string>

Func<string> temp = () => {return "test";};

This can be done in one line by a bit of casting or using the delegate constructor to establish the type of the lambda followed by an invocation.

string temp = ((Func<string>)(() => { return "test"; }))();
string temp = new Func<string>(() => { return "test"; })();

Note: Both samples could be shorted to the expression form which lacks the { return ... }

Func<string> temp = () => "test";
string temp = ((Func<string>)(() => "test"))();
string temp = new Func<string>(() => "test")();

Solution 2:

You are attempting to assign a function delegate to a string type. Try this:

Func<string> temp = () => {return "test";};

You can now execute the function thusly:

string s = temp();

The "s" variable will now have the value "test".

Solution 3:

Using a little helper function and generics you can let the compiler infer the type, and shorten it a little bit:

public static TOut FuncInvoke<TOut>(Func<TOut> func)
{
    return func();
}

var temp = FuncInvoke(()=>"test");

Side note: this is also nice as you then are able to return an anonymous type:

var temp = FuncInvoke(()=>new {foo=1,bar=2});

Solution 4:

you can use anonymous method with argument :

int arg = 5;

string temp = ((Func<int, string>)((a) => { return a == 5 ? "correct" : "not correct"; }))(arg);