Delegates and Lambda Expressions

A lambda expression is a method without a declaration – so no access modifier, no return value declaration and no name.

Why should I use a lambda expressions ?
1. Reduces typing – I don’t need to specify the name of the function, its return type, and its access modifier
2. Convenient. When reading the code, you don’t need to look elsewhere for the method’s definition

Consider the function:

bool IsGreaterThanFive(int x)
{
return x > 5;
}

This can be re-written as the lambda expression: n => n > 5

Lambda expression structure
Parameters => Executed code
e.g. n => n > 5
n : is the input to the expression

n > 5 : is the code that will be executed
the expression will return a bool true/false
true if n > 5, false if n < 5

=> : Compiler syntactic sugar. The compiler takes both the input argument ( n ) and the code that will be executed ( n < 5  ) and creates a function under-the-hood

bool IsGreaterThanFive(int x)
{
return x > 5;
}

Example lambda expression

DelegateWithLambda

 

Posted in Uncategorized

Leave a comment

Design a site like this with WordPress.com
Get started