Hi everyone! I'm new at C# programming, and i can not understand very well how Lambda expression works and/or what is used for.
Thank you!
Hi everyone! I'm new at C# programming, and i can not understand very well how Lambda expression works and/or what is used for.
Thank you!
For further actions, you may consider blocking this person and/or reporting abuse
Heru Hartanto -
Grant Riordan -
0x3d Site -
Cesar Aguirre -
Top comments (4)
These five years olds are too smart, they can understand functional programming :-D
How would I explain it to a 5 year old who doesn't even know what programming is?
You have three toy buttons: bark, squeal, roar (the names + the functions). Every time you push one of them something magic happens (the function body) and you hear the corresponding sound (the function result). So every button has a function, a purpose.
Your little brother manages to erase the label "roar" from the third button so you decide to apply on it one of your Batman stickers.
You know that if you press the "Batman" button you're still going to hear a roar, no matter what the new name says.
Even if you remove the sticker and lend it to one of your friends, anytime they're going to press the button they're going to hear a roar.
Are you familiar with JavaScript? If so, think of Lambda expressions as anonymous JavaScript functions.
Where in JavaScrip you would have
in C# you would have
You would use Lambda expressions anywhere where you would need to pass a function.
Hope that helps!
A lambda expression is an anonymous function (meaning a function without a name) which takes some parameters and a "function" (actually it's a statement or expression).
This is a simple exmaple from C# Programming Guide
On the left side you see two variables x and y in parenthesis. These are your parameters, on the right side you see the comparison x==y (the "function"). You could rewrite this to:
So you cold say lambda expression contain only the import stuff and drop the part of your code that doesn't contain the logic.
Lambda expressions can make your code easier to read and by that make it look cleaner.
A quick example (in Java, but that shouldn't be a problem):
Even if you dont't know all the methods it's pretty easy to guess what this code does isn't it? (the flatMap thing just makes one list out of a nested one ;))
Feel free to ask if anything is unclear :)
Lambdas are, in a nutshell, functions. Let's say you have a function like this one:
you can rewrite it like this:
Having defined
stringDelegate
like this:One peculiarity is the variable capture: lambdas can capture - close over - variables in scope during lambda definition. So this works:
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:
Will give you this output: