This blog is a knowledge base...where I clip cool tricks and urls

Lambda Expression for C# 3.0

"A lambda is an inline expression or statement block with a concise syntax that can be used in C# 3.0 and later wherever a delegate type is expected" . In a certain way we can consider Lambda Expressions as an evolution of the anonymous methods.

Look the examples below, at first sight the syntax looks very weird but when you know how they are built and you get used, you will see that it's extremely easy.

x => x + 1

x => { return x + 1; }

(x, y) => x == y

(int x, int y) => x * y

() => ExecuteAnyMethod();

Maybe you already noticed that a lambda consist of a list of input parameters, the operator "=>" (goes to) and a expression or statement. In the form of:

(input parameters) => Expression or Statement.

The list of parameters is optional, and you don't need to specify the types of the parameters in the cases where the type can be inferred. Parenthesis are also optional when we only specify one parameter.

 blog it

No comments: