.NET Reference

Microsoft Documentation

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.

delegate void MyDelegate(string message);

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

Built-in Delegate Types

The .NET Framework provides several generic built-in delegate types to simplify common scenarios: