C# Lambda Functions: returning data

Drew R picture Drew R · Mar 20, 2013 · Viewed 30.3k times · Source

Am I missing something or is it not possible to return a value from a lambda function such as..

Object test = () => { return new Object(); };

or

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

I get a build error "Cannot convert lambda expression to type 'string' because it is not a delegate type".

It's like this syntax assigns the lambda rather than the result of the lambda, which I did not expect. I can achieve the desired functionality by assigning the function to a Func and calling it by name, but is that the only way?

Please no "why would you need to do this?" regarding my example.

Thanks in advance!

Answer

Konrad Rudolph picture Konrad Rudolph · Mar 20, 2013

It’s possible but you are trying to assign a lambda to a string. – You need to invoke the lambda:

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

The error message actually says it all:

Cannot convert lambda expression to type 'string'

… that’s exactly the issue here.

If you want to invoke the lambda inline – but really: why? – you can do that too, you just need to first make it into a delegate explicitly:

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