DEV Community

Discussion on: Explain Lambda expressions like I'm five

Collapse
 
mindflavor profile image
Francesco Cogno • Edited

Lambdas are, in a nutshell, functions. Let's say you have a function like this one:

static string sayHello1(string name)
{
    return "Hello " + name + "!";
}

you can rewrite it like this:

stringDelegate sayHello2 = name => "Hello " + name + "!";

Having defined stringDelegate like this:

delegate string stringDelegate(string name);

One peculiarity is the variable capture: lambdas can capture - close over - variables in scope during lambda definition. So this works:

var myName = "Karl";
stringDelegate sayHello3 = (name) => "Hello " + name + ", I'm " + myName + "!";

This is very useful: if it were a function we would have to add it as parameter (or use a global variable in languages that support it).

Notice that in C# strings are references so if you later change the value you do it in the lambda too.

Try this code:

var myName = "Karl";
stringDelegate sayHello3 = (name) => "Hello " + name + ", I'm " + myName + "!";
System.Console.WriteLine(sayHello3("Frank"));
// we change the value referenced by myName
myName = "Peter";
System.Console.WriteLine(sayHello3("Jason"));

Will give you this output:

Hello Frank, I'm Karl!
Hello Jason, I'm Peter!