Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Lambda Functions: returning data

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!

like image 733
Drew R Avatar asked Mar 20 '13 13:03

Drew R


1 Answers

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"; }))();
like image 191
Konrad Rudolph Avatar answered Sep 20 '22 11:09

Konrad Rudolph