To describe in simple words Lambda expressions are functions which don’t have a name .Lambda expressions have the following characteristics.
- We can assign a lambda expression to a delegate.The advantage is that we don’t need to create a new method if we want to create the method just for assigning to a delegate .
- Lambda expressions can take input parameters and return a value.Their syntax is more concise than anonymous methods.
Let’s say we have a delegate variable defined as
delegate string SubStr(string name);
then we can assign a lambda expression to the delegate variable as
SubStr substr = x => x.Substring(0, 5);
Now if we call the delegate then it will return the first 5 digits of the parameter.We can call the lambda expression as
substr(“hello!”)
Below is the complete code which defines a delegate and assigns a lambda expression to it.
class Program
{
delegate string SubStr(string name);
static void Main(string[] args)
{
SubStr substr = x => x.Substring(0, 5);
Console.WriteLine(substr(“hello!”));
Console.ReadLine();
}
}
If we are defining a method only to assign it to a delegate then lambda expressions are the appropriate solution.
Leave a Reply