We have always declared delegates in by using the below signature.
Process processDelegate = new Process(ProcessTask);
There is nothing wrong in defining the delegates like above, except when you need to define so many such delegates. Then you will realize the pain of declaring so many such delegates.
Delegates are just function pointers, so defining like above matching method signature can be eliminated by using generic delegates.
Using generic delegate you can save on delegate definition like below:
So using generic delegates is simple and it eliminates the need for defining the delegates separately. Going further there are 3 different types of generic delegates:
- Func delegates
- Action delegates
- Predicate delegates
Let’s go one by one.
Func generic delegates are a delegate to a method which accepts zero to sixteen parameters and returns a value always.
The func delegates can be a delegate to a method accepting up to 16 input parameters and returns a value.
Func delegate example in C#.NET:
Func <int, int, long> funcDelegate = ProcessTask;
long result = funcDelegate(1,2);
Action delegates can be a delegate to a method accepting up to 16 input parameters and returning no value. Action generic delegates are similar to Func delegates expect that they don’t return any value. Action delegate return type is always void.
Action delegate example in C#.NET:
Func <int, int> actionDelegate = ProcessTask;
Predicates can be delegates to a method accepting a parameter and retuning a Boolean value.
Predicate are extensively used in lamda expression to filter the results. In the below example, predicates are used to get the list of managers from the employee list.
(Employee e) =>
return e.Designation == "Manager";