10

I'm defining a lambda and calling it, by appending "()", immediately.

Try:

int i = (() => 0) ();

Error:

Error CS0119: Expression denotes a anonymous method', where amethod group' was expected

Why is that?

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
SpaceMonkey
  • 4,143
  • 5
  • 38
  • 60

2 Answers2

15

You're not "defining a lambda".. you're wrapping parenthesis around what you think is one.

The compiler doesn't infer this type of thing. It needs context. You give it context by assigning or casting the representation of the lambda to a delegate type:

Func<int> f = () => 0;
int i = f();

Thats clear context. If you want an unclear one.. this sort of thing also works:

int i = ((Func<int>)(() => 0))();
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
9

A lambda just does not support being executed. A delegate supports being executed. A lambda expression can be implicitly converted to a delegate type. In case no such conversion is requested there is no "default" delegate type. Since .NET 2 we normally use Action and Func for everything but we could use different delegate types.

First convert to a delegate, then execute:

((Func<int>)(() => 0))()

One could argue that C# should default to using Action and Func if nothing else was requested. The language does not do that as of C# 5.

usr
  • 168,620
  • 35
  • 240
  • 369