Delegates
Delegates are type-safe function pointers. They are used to pass methods as arguments to other methods. Delegates are the basis for events and callback methods in .NET.
Overview
A delegate is an object that represents references to methods with a particular parameter list and return type. When a delegate object is created, it can be associated with a particular method. You can also associate a delegate object with a list of methods. This list is called a invocation list.
Delegates are declared using the delegate
keyword. They are very similar to method signatures.
Declaring a Delegate
To declare a delegate, you use the delegate
keyword, followed by the return type, delegate name, and parameter list.
This declares a delegate named MyDelegate
that takes a single string
argument and has no return value (void
).
Instantiating a Delegate
Once a delegate is declared, you can create an instance of it and associate it with a method that matches the delegate's signature.
// Assume MyDelegate is declared as above
MyDelegate handler = new MyDelegate(MyMethod);
// Shorthand syntax is also common:
MyDelegate handler = MyMethod;
Invoking a Delegate
You can invoke the method(s) associated with a delegate by calling the delegate instance as if it were a method.
// Assuming 'handler' is an instance of MyDelegate
handler("Hello, World!");
Multicast Delegates
Delegates can also point to a chain of methods. This is known as a multicast delegate. You can add methods to the invocation list using the +
or +=
operators, and remove them using the -
or -=
operators.
MyDelegate handler1 = MethodA;
MyDelegate handler2 = MethodB;
// Create a multicast delegate
MyDelegate multiHandler = handler1 + handler2;
// Invoke all methods in the chain
multiHandler("Invoking multiple methods");
// Remove a method
multiHandler -= handler1;
multiHandler("Handler1 removed");
Common Use Cases
- Event Handling: Delegates are fundamental to .NET's event model. An event is essentially a delegate.
- Callback Methods: Passing a delegate to another method allows that method to "call back" to your code at a later time or when a certain condition is met.
- Asynchronous Programming: Delegates play a role in asynchronous operations, enabling you to specify what happens when an operation completes.
Built-in Delegate Types
The .NET Framework provides several generic built-in delegate types to simplify common scenarios:
Action<T1, T2, ...>
: Represents a method that takes one or more parameters and returnsvoid
.Func<TResult>
,Func<T1, TResult>
,Func<T1, T2, TResult, ...>
: Represents a method that takes zero or more parameters and returns a value.Predicate<T>
: A specific type ofFunc
delegate that represents a method taking one parameter and returning abool
.