C# Lambda Functions: returning data
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"; }))();
Drew R
Updated on March 21, 2020Comments
-
Drew R about 4 years
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!
-
sloth about 11 yearsAssigning a lambda expression to an implicitly-typed variable will not work.
-
Konrad Rudolph about 11 years@DominicKexel Ah, very true.
-
Drew R about 11 yearsAh that was quick. was just editing my question when you answered. Is it possible to Invoke the lambda inline rather than assigning to a Func<string>? Thanks!
-
Drew R about 11 yearsThanks Konrad. And because I have a nice wide screen and like to write lines like:
_queuePath = new Func<string>(() => { if (Directory.Exists(currentLineSplit[1])) { return currentLineSplit[1]; } else { throw new Exception("Queue path does not exist."); } })();
-
basher almost 9 years@DrewR why not just use the conditional operator?
_queuePath = (Directory.Exists(currentLineSplit[1])) ? currentLineSplit[1] : throw new Exception("Queue path does not exist.");