In C#, a delegate is a type that holds references to methods. These can point to static methods, instance methods, or lambda expressions. They are commonly used for implementing callback mechanisms, event handling, and generic method implementations.
Key characteristics of delegates include:
- Type Safety: Delegates are strongly typed, meaning their method signatures are determined at compile time.
- Multicasting: Multiple method calls can be linked to a single delegate. When invoked, all linked methods execute in sequence.
- Flexibility: Delegates allow passsing methods as parameters to other functions, enhancing modularity and flexibility.
- Enonymous Methods: Lambda expressions and anonymous methods can define delegates without explicit method definitions.
A delegate is a reference type, essentially a class that stores pointers to methods. Invoking a delegate executes the referenced method immediately.
The process of using delegates involves three steps:
- Define the delegate
- Instantiate the delegate
- Invoke the delegate
Custom Delegate Definition
namespace Example
{
public delegate double Calculator(double a, double b);
internal class Program
{
public static double Add(double a, double b)
{
return a + b;
}
public static double Subtract(double a, double b)
{
return a - b;
}
static void Main(string[] args)
{
Calculator calc = new Calculator(Add);
double result1 = calc(12.0, 24.0);
Console.WriteLine($"Addition result: {result1:F2}");
Calculator calc2 = new Calculator(Subtract);
double result2 = calc2(24.0, 12.0);
Console.WriteLine($"Subtraction result: {result2:F2}");
}
}
}
Generic Delegate Types
- Action: Represents methods with no return value. Accepts 0 to 16 parameters.
- Func<>: Represents methods with a return value. Accepts 0 to 16 parameters, with the last being the return type.
- Predicate<>: A specialized form of
Func<T, bool>, used for methods accepting one parameter and returning a boolean.
namespace Example
{
internal class Program
{
public void Display()
{
Console.WriteLine("Display called");
}
public int Calculate(int x, int y)
{
return x + y;
}
static void Process(int value, Action action)
{
action();
Console.WriteLine(value);
}
static int Compute(int baseValue, Func<int, int, int> operation, int param1, int param2)
{
return baseValue + operation(param1, param2);
}
static void Main(string[] args)
{
Program instance = new Program();
int baseVal = 0;
int num1 = 100;
int num2 = 100;
Process(baseVal, instance.Display);
int result = Compute(20, instance.Calculate, 40, 40);
Console.WriteLine($"Final result: {result}");
}
}
}
Multicast Delegates
Multicast delegates support adding multiple methods via the += operator and removing them using -=. It's also possible to combine two delegates of the same type into one.