tags:

views:

258

answers:

6

I have pasted some code from Jon Skeet's C# In Depth site:

static void Main()
{
    // First build a list of actions
    List<Action> actions = new List<Action>();
    for (int counter = 0; counter < 10; counter++)
    {
        actions.Add(() => Console.WriteLine(counter));
    }

    // Then execute them
    foreach (Action action in actions)
    {
        action();
    }
}

http://csharpindepth.com/Articles/Chapter5/Closures.aspx

Notice the line:

actions.Add( ()

What does the () mean inside the brackets?

I have seen several examples of lambda expressions, delegates, the use of the Action object, etc but I have seen no explanation of this syntax. What does it do? Why is it needed?

+4  A: 

That's a lambda expression without parameters.

bruno conde
+1  A: 

It denotes anonymous function without a parameter.

Ramesh
+11  A: 

This is shorthand for declaring a lambda expression which takes no arguments.

() => 42;  \\ Takes no arguments returns 42
x => 42;   \\ Takes 1 argument and returns 42
(x) => 42; \\ Identical to above
JaredPar
dang syntax highlighting bug
Will
@Will thanks, I work in too many languages on a daily basis
JaredPar
+1  A: 

From MSDN. An Expression lambda takes the form (inputs)=>expression. So a lambda like ()=>expression denotes there are no input parameters. Which the signature for Action takes no parameters

JoshBerke
+1  A: 

What this line does is to add an anonymous Action to the list using lambda expressions, that takes no parameter (that's the reason why the () are there) and returns nothing, due to the fact that it prints only the actual value of the counter.

Giu
A: 

I think of lambas like this:

(x) => { return x * 2; }

But only this is important:

(x) => { return x * 2; }

We need the => to know that it's a lambda instead of casting, and thus we get this:

x => x * 2

(sorry for not formatting code as code, that's because you can't make things bold in code..)

svinto