Lambda expressions

Lambda expressions were introduced to C# in 3.0 version. Lambda expressions are based upon anonymous functions and a lambda expression is a shorter way to represent an anonymous method. 

In Chapter 5, Creating and Implementing Events and Callbacks, in the Initiate delegate using anonymous functions section, we looked at how we can create anonymous functions in C# using the delegate keyword. In a nutshell, just to recap, using anonymous methods, we can create an inline method in some code, assign it to a variable, and pass it around.

In Chapter 5, Creating and Implementing Events and Callbacks, in the Lambda expressions section, we looked at how we can convert an anonymous function into its equivalent lambda expression. However, just to recap, let's go through the following code example, in which we will first create an anonymous function and then create a lambda expression for the same:

Func<int, int> anonymousFunc = delegate (int y)
{
return y * 5;
};
Console.WriteLine(anonymousFunc(1));'.

In the preceding code, we declared a delegate function of the Func<T,T> format. This implies that this function takes an input of int and returns an integer output. Hence, the output for the preceding operation would be 1 * 5, that is, 5.

Now, if we need to write the same code using a lambda expression, we can use the following code syntax:

Func<int, int> anonymousFuncLambda = y => y * 5; 
Console.WriteLine(anonymousFuncLambda(1));

Please also note the usage of the => notation in a lambda expression. This notation translates into becomes or for which.

If we execute the two code blocks, we will notice that the results of the operations are the same. However, with lambda expressions, we end up with much cleaner code and avoid a lot of code typing. In the next section, we will look at extension methods.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.75.217