19 May 2015

generic delegates in c#.net

We have always declared delegates in by using the below signature.

delegate void Process(int input1, int input2);
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:

Action<intint> processDelegate = ProcessTask;

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:

  1. Func delegates
  2. Action delegates
  3. Predicate delegates

Let’s go one by one.

Func delegates

Func generic delegates are a delegate to a method which accepts zero to sixteen parameters and returns a value always.

public delegate TResult Func<T, TResult>(T arg);

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:
public  long ProcessTask(int 1 input1, int input2)
{
}
Func <intintlong> funcDelegate = ProcessTask;
long result = funcDelegate(1,2);

Action delegates

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.

public delegate void Action<in T1, in T2>(T1 arg1, T2 arg2);
Action delegate example in C#.NET:
public void ProcessTask(int 1 input1, int input2)
{
}
Func <intint> actionDelegate = ProcessTask;
actionDelegate(1, 2);

Predicate delegates

Predicates can be delegates to a method accepting a parameter and retuning a Boolean value.

public delegate bool Predicate<in T>(T obj);

Predicate are extensively used in a lambda expression to filter the results. In the below example, predicates are used to get the list of managers from the employee list.

Predicate<Employee> managerFinder= 
   (Employee e) => 
      {
         return e.Designation == "Manager"
      };

No comments:

Post a Comment