Search⌘ K
AI Features

Delegates

Explore how delegates in C# let you treat methods as data by assigning method references to delegate objects, enabling dynamic invocation of multiple methods. Understand static and instance method delegates, combining delegates, passing them as parameters, and using generics to create flexible, reusable code structures.

In C#, we are used to passing data like integers or strings into methods. Delegates allow us to treat behavior as data. By assigning a method to a delegate, you can pass an entire block of logic around your application, allowing methods to execute dynamically provided behaviors.

Delegates are objects that point to methods. They hold references to method definitions, and invoking a delegate executes all methods it references.

Delegates can reference methods
Delegates can reference methods

We declare delegates using the delegate keyword followed by a specific method signature and return type.

delegate void MessagePrinter();

We defines a delegate type named MessagePrinter that matches any method returning void with no parameters. The following example details the syntax:

Decomposition of delegate declaration
Decomposition of delegate declaration

We can create a delegate inside a class or directly inside a namespace because delegates are essentially classes that implicitly inherit from the Delegate or MulticastDelegate class.

Note: We cannot create a class and make it inherit from Delegate or MulticastDelegate. Only compilers and the platform can inherit explicitly from the mentioned classes. We must use the delegate keyword.

After declaring a delegate, we can create instances of it, attach method pointers, and call the delegate:

Delegate usage illustration
Delegate usage illustration

Delegates with static methods

We can ...