C# delegate
In C#, a delegate is a type that represents a reference to a method. It is similar to a function pointer in C and C++. Delegates allow methods to be passed as parameters, returned from methods, and assigned to variables. They are often used in event handling and asynchronous programming.
A delegate is declared using the delegate
keyword, followed by the return type, name, and parameter list of the method it references. For example, the following code declares a delegate named Calculate
that represents a method that takes two int
parameters and returns an int
:
delegate int Calculate(int x, int y);
Once a delegate type has been defined, it can be used to create delegate instances that can reference any method with a compatible signature. For example:
int Add(int x, int y) { return x + y; } Calculate calc = new Calculate(Add); int result = calc(3, 4); // result == 7
In this example, the Add
method is assigned to a delegate instance named calc
. The delegate is then invoked like a method, passing in the arguments 3
and 4
.
Delegates can also be multicast, meaning they can reference multiple methods. To create a multicast delegate, multiple delegate instances can be combined using the +
or +=
operator. For example:
int Subtract(int x, int y) { return x - y; } Calculate calc = new Calculate(Add); calc += new Calculate(Subtract); int result = calc(3, 4); // result == 7 (Add) then -1 (Subtract)
In this example, a delegate instance representing the Subtract
method is added to the existing delegate instance calc
. When the delegate is invoked, both the Add
and Subtract
methods are called in order.