Generic Delegates
Generic Delegate
Before discussing generic delegates, it takes an example of delegates. Delegate is a pointer to an event handler function.
Suppose we have 3 functions as below
To execute these functions through delegates, we need to declare 3 delegates as below
And we can call these functions through delegates as shown below
And we will get below result
This is an example of normal delegates, and you would have noticed that we had to declare delegates before using them by creating object.
To overcome this issue, .NET 3.5 framework comes to inline declaration and creating object as same time – generic delegates.
There are 3 types of generic delegates .NET provides.
1. Function delegate
2. Action delegate
3. Predicate
Function delegate can accept multiple parameters, and last parameter is return type. Function delegate always return a value. Function delegate can accept upto16 parameters of different types.
Action delegate can accept multiple parameters of different data types, but action delegate doesn’t return any values back to caller. Action delegate also accept upto 16 parameters of different types.
Predicate delegate only accepts one parameter and return Boolean values only.
Let’s re-write above code using generic delegates.
And output of both will be same
In one place, we have used old method to declare and creating delegate, but next we declare and created function delegate in-line.
We can also use generic delegates of two other methods and you will get same output.