In C#, a delegate is a type-safe function pointer that allows methods to be referenced and invoked dynamically. It provides a way to treat methods as objects, enabling scenarios such as event handling, callbacks and functional-style programming.
- A delegate defines the signature of methods it can point to.
- It can reference both static and instance methods.
- Delegates are type-safe, meaning the method signature must match the delegate declaration.
- They are the foundation of events and anonymous functions in C#.
When to Use Delegates
- For implementing callbacks.
- For handling events.
- For writing flexible, reusable code where behavior can be passed as parameters.
- For functional-style programming with LINQ and lambdas.
Declaration of Delegates
Delegate type can be declared using the delegate keyword. Once a delegate is declared, delegate instance will refer and call those methods whose return type and parameter-list matches with the delegate declaration.
Syntax:
[modifier] delegate [return_type] [delegate_name]([parameter_list]);
- modifier: Defines the accessibility of the delegate (public, private, internal, etc.). It is optional.
- delegate: The keyword used to declare a delegate.
- return_type: The type of value returned by the methods referenced by the delegate (can also be void).
- delegate_name: The identifier you assign to the delegate.
- parameter_list: Defines the parameters the delegate requires. The methods assigned must match this list exactly.
Example:
OutputMessage: Hello from delegate!
Explanation:
- MyDelegate is defined to point to methods that take a string parameter and return void.
- The DisplayMessage method matches the delegate signature.
- The delegate instance del references the method and is invoked like a method call.
Multicasting of a Delegate
Delegates can reference multiple methods at once using the + or += operator. Such delegates are called multicast delegates.
Properties:
- Delegates are combined and when you call a delegate then a complete list of methods is called.
- All methods are invoked in the order they were added to the delegate (invocation order).
- '+' or '+=' Operator is used to add the methods to delegates.
- '–' or '-=' Operator is used to remove the methods from the delegates list.
OutputMethod A executed
Method B executed
Note:
If the delegate has a return value, only the result of the last method in the invocation list is returned.
Delegates with Return Types
Delegates can also be used with methods that return values.