15

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!

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Drew R
  • 2,988
  • 3
  • 19
  • 27
  • @IAbstract Your edit completely changed the question so I rolled it back. – Konrad Rudolph Mar 20 '13 at 13:55
  • @KonradRudolph: odd ... I was *attempting* to remove the last 2 lines. Thanks for catching that. :) – IAbstract Mar 20 '13 at 16:04
  • Possible duplicate of [How to return value with anonymous method?](http://stackoverflow.com/questions/10520892/how-to-return-value-with-anonymous-method) – Roflo Nov 18 '15 at 17:26

1 Answers1

35

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"; }))();
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 1
    Assigning a lambda expression to an implicitly-typed variable will not work. – sloth Mar 20 '13 at 13:50
  • @DominicKexel Ah, very true. – Konrad Rudolph Mar 20 '13 at 13:50
  • Ah 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? Thanks! – Drew R Mar 20 '13 at 13:52
  • Thanks Konrad. And because I have a nice wide screen and like to write lines like: `_queuePath = new Func(() => { if (Directory.Exists(currentLineSplit[1])) { return currentLineSplit[1]; } else { throw new Exception("Queue path does not exist."); } })();` – Drew R Mar 20 '13 at 14:00
  • 1
    @DrewR why not just use the [conditional operator](https://msdn.microsoft.com/en-us/library/ty67wk28.aspx)? `_queuePath = (Directory.Exists(currentLineSplit[1])) ? currentLineSplit[1] : throw new Exception("Queue path does not exist.");` – basher Apr 27 '15 at 18:29