Delegate
The delegate is a reference type that can be used to encapsulate a method with a specific signature. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure.
The delegate is declared using the keyword delegate:
class Program
{
delegate int MyDelegate(int a, int b);
static void Main(string[] args)
{
MyDelegate del = new MyDelegate(Sum);
int res = del(1, 3); // res = 4
}
static int Sum(int a, int b)
{
return a + b;
}
}
Starting from c# 2.0 is possible to declare a delegate omitting the new clause:
MyDelegate del = Sum;
From c# 2.0 is also possible to declare a delegate with a anonymous method. A anonymous method is nothing else a block of code passed to the delegate as parameter:
MyDelegate del = delegate(int a, int b) { return a + b; };
Lambda Expressions
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.
All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read "x goes to x times x."
The lambda expression can be assigned to a delegate type as follows:
MyDelegate del = (int a, int b) => { return a + b; };
or in the contract form:
MyDelegate del = (int a, int b) => a + b;
556c5e69-5289-459e-8abe-a181dfdd0824|0|.0