C# Lambda expressions

Lambda expressions are anonymous methods that does not have access modifiers, name or a return. They are used for convenience (less code) and makes code more readable.

Lambda expression takes the form below –

arg => expression //spelled as argument goes to expression

This can be used in 3 distinct ways as below –

() => expression

x  => expression

(x,y,z) => expression //>=1 arguments

Lets see a simple example where we want to find the square of a number and how we can use Lambda expression to achieve this without using a method. Another interesting thing to note is we use Generic Delegates in conjunction with Lambda expressions to achieve this.

public namespace simpleLambda{

public static void Main (string[] args){

Func<int, int> square= n => n* n; //implements a generic delegate that represents a method signature

//’square’

Console.WriteLine(square(4));

}

}