Object Oriented Programming

General C#

Interview Questions

Lambda Expressions in C#

(You should have a good understanding of Delegates, if you want to understand Lambda Expressions.)

What is a Lambda Expression:

Lambda Expressions are nothing but anonymous methods, using which you can create delegates and expression trees.(Expression trees needs will be explained in a separate article. )

If Lambda expressions are just anonymous methods why do we need them? What is the use of it?

Basically Lambda Expressions simplifies the anonymous methods syntactically. The whole code can be concise and neat. It takes another step ahead of Anonymous functions.
So it is a good idea to read Anonymous Methods before before moving forward.

The delegate is replaced by x=>x*x. As you can see the syntax is much simplified. => is the Lambda operator. It is read 'goes to'.
So the expression is read as 'x goes to x*x'. As you can see the right side got only one statement in the example. Whatever is the right side
is evaluated to, would be the return type of the expression. If there are more than one statement then you may rewrite the expression as

When there are multiple statements in your Lambda Expression you should include the whole block in the curly brackets.And there should be
explicit return statement if the lambda expression supposed to return anything. Please note that the method GenericCalculation expects a delegate which takes one integer parameter and expects a return type
of integer. And that is the reason we are returning an integer in this example.