Drew R
Drew R

Reputation: 3088

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!

Upvotes: 15

Views: 36904

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 546183

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"; }))();

Upvotes: 35

Related Questions