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?
This is shorthand for declaring a lambda expression which takes no arguments.