Delegates¶
A delegate is like a function pointer in C or C++, meaning it can store references to methods and call them dynamically.
There are three steps involved while working with delegates: 1. Declare a delegate type (defines the method signature). 2. Assign a method to the delegate. 3. Call the delegate just like a method.
Passing delegates¶
You can even pass a delegate as an argument to another method.
Multicast Delegate¶
The delegate can point to multiple methods. A delegate that points multiple methods is called a multicast delegate.
This is done by adding functions to an invocation list using operators:
- +, add a function to the list
- +=, add a function to the list
- -, remove a function from the list
- -=, remove a function from the list
Generic delegates¶
A generic delegate can be defined the same way as a delegate but using generic type parameters or return type. The generic type must be specified when you set a target method.
Built-in generic delegates: Func, Action And Predicate¶
Whenever we use delegates, we have to declare a delegate, initialize it, and then call a method with a reference variable.
Funcdelegate takes zero or more parameters,returns a value.Actiontakes zero or more parameters, isvoid.Predicatetakes zero or more parameters, returnsbool.
Anonymous methods¶
An anonymous method is a method without a name. Instead of defining a separate named method, you can define an inline method directly inside a delegate.
Limitations of anonymous methods: - No reusability - No jump statements like goto, break or continue. - No ref or out parameters of an outer method. - No access unsafe code. - Cannot be used on the left side of the is operator.
Use cases of delegates¶
- Event Handling (e.g., Button Click in UI apps).
- Callbacks (executing a method after another completes).
- LINQ & Functional Programming (higher-order functions).
- Strategy Pattern & Custom Logic Switching.