Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does () => {} mean?

Tags:

c#

I was reading Pulling the switch here and came across this code.

Can somoone please explain what is () => {} and what should I read up to understand that line of code?

var moveMap = new Dictionary<string, Action>()
{
    {"Up", MoveUp},
    {"Down", MoveDown},
    {"Left", MoveLeft},
    {"Right", MoveRight},
    {"Combo", () => { MoveUp(); MoveUp(); MoveDown(); MoveDown(); }}
};

moveMap[move]();
like image 669
Magic Avatar asked May 04 '12 10:05

Magic


2 Answers

It's a lambda expression:

All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block

Basically you are constructing a new, temporary function here that just calls a combination of two of the other functions.

As seen above, the () on the left side means that it has an empty parameter list (just like your other functions). The {} on the right means that it executes several statements inside a block, which makes it a "statement lambda" that is called for its side effects, in contrast to an "expression lambda", which computes a value.

like image 195
Niklas B. Avatar answered Oct 11 '22 21:10

Niklas B.


() => {/*code*/} is a lambda expression, a convenient way to create an anonymous delegate that takes zero parameters. Essentially it creates a callable piece of code that in your case moves up twice and then moves down twice.

You are not limited to lambdas without parameters - you can create ones with arguments:

Action<string> callable = (name) => {Console.WriteLine("Hello, {0}!", s);};
callable("world");
callable("quick brown fox");
like image 34
Sergey Kalinichenko Avatar answered Oct 11 '22 22:10

Sergey Kalinichenko