C# Delegates overview with examples
Delegates are similar to C++ function pointers, but delegates are fully object-oriented, and unlike C++ pointers to member functions, delegates encapsulate both an object instance and a method. Delegates have the following properties:
- Delegates allow methods to be passed as parameters.
- Delegates can be used to define callback methods.
- Delegates can be chained together; for example, multiple methods can be called on a single event.
- Methods don’t have to match the delegate type exactly. For more information, see Using Variance in Delegates.
- Lambda expressions are a more concise way of writing inline code blocks. Lambda expressions (in certain contexts) are compiled to delegate types. For more information about lambda expressions, see Lambda expressions.
Simple Example:
using System;
// Define a delegate named MathOperationDelegate
delegate int MathOperationDelegate(int a, int b);
class Program
{
// Method that matches the signature of MathOperationDelegate
static int Add(int a, int b)
{
return a + b;
}
// Another method that matches the signature of MathOperationDelegate
static int Subtract(int a, int b)
{
return a - b;
}
static void Main(string[] args)
{
// Create delegate instances pointing to methods
MathOperationDelegate operation1 = Add;
MathOperationDelegate operation2 = Subtract;
// Use delegate instances to perform operations
int result1 = operation1(5, 3); // This will call Add(5, 3)
int result2 = operation2(5, 3); // This will call Subtract(5, 3)
Console.WriteLine("Result of addition: " + result1); // Output: 8
Console.WriteLine("Result of subtraction: " + result2); // Output: 2
}
}