Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does () mean in a lambda expression when using Actions?

Tags:

c#

lambda

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?

like image 909
Alex Avatar asked Feb 26 '09 14:02

Alex


People also ask

What does => mean in lambda?

In lambda expressions, the lambda operator => separates the input parameters on the left side from the lambda body on the right side.

What are the three parts of a lambda expression?

A lambda in Java essentially consists of three parts: a parenthesized set of parameters, an arrow, and then a body, which can either be a single expression or a block of Java code.

How do lambda expressions work?

A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.

Can you explain the syntax of lambda expression?

Java Lambda Expression Syntax Java lambda expression is consisted of three components. 1) Argument-list: It can be empty or non-empty as well. 2) Arrow-token: It is used to link arguments-list and body of expression. 3) Body: It contains expressions and statements for lambda expression.


1 Answers

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 
like image 123
JaredPar Avatar answered Sep 22 '22 23:09

JaredPar