A delegate is a type that represents a reference to a method with a specific signature. It is similar to a function pointer in C/C++. A delegate can be used to encapsulate a method call and pass it as an argument to another method or store it as a field or property.
Here's an example:
public delegate int CalculationDelegate(int x, int y);
public class Calculator
{
public int Add(int x, int y)
{
return x + y;
}
public int Multiply(int x, int y)
{
return x * y;
}
}
public class Program
{
public static void Main(string[] args)
{
Calculator calculator = new Calculator();
CalculationDelegate add = calculator.Add;
int result = add(2, 3); // result = 5
CalculationDelegate multiply = calculator.Multiply;
result = multiply(2, 3); // result = 6
}
}
An anonymous method is a method without a name that can be defined inline with the code using a delegate. It allows you to define a method without having to create a separate method declaration.
Here's an example:
CalculationDelegate add = delegate (int x, int y)
{
return x + y;
};
int result = add(2, 3); // result = 5
A lambda expression is a concise way to define an anonymous method. It is a shorthand notation that allows you to define a method inline with the code using the => operator. Lambda expressions are typically used with delegates, but they can also be used with other types that define a single method, such as Func and Action.
Here's an example:
CalculationDelegate add = (x, y) => x + y;
int result = add(2, 3); // result = 5
Lambda expressions are often used with LINQ queries, which use functional programming techniques to filter, sort, and transform data.