Click here to Skip to main content
11,705,052 members (57,156 online)
Click here to Skip to main content

Delegates & its 5 Modern Flavors (Func, Action, Predicate, Converter, Comparison)

, 10 Mar 2014 CPOL 33.5K 273 56
Rate this:
Please Sign up or sign in to vote.
.NET Delegates & its 5 different features (Func, Action, Predicate, Converter, Comparison)

Introduction

Delegate is a very powerful feature available in the .NET Framework. In this article, we will explore delegate & its new features which are being introduced in the framework. I will be using Visual Studio 2013 for coding sample code, assuming that you do have basic knowledge of .NET C# code.

I will be explaining the following flavors in this articles:

  1. Func
  2. Action
  3. Predicate
  4. Converter
  5. Comparison

I would like to get feedback on this article. Please feel to share your comments or you can also email me at shettyashwin@outlook.com. If you like this article, please don't forget to rate it.

Background

As part of the Interview panel, I have been asked to interview a lot of candidates for the opening we had. At the time of interview when questions were asked on delegates & its features, very few candidates were able to answer this question. Even one of my team members was surprised when I optimized his code & started using action delegate. Hence, I decided to write this article which shares some details on delegates & some of its features.

What are Delegates?

If I can put it into simple words, Delegate is a pointer to a method. Delegate can be passed as a parameter to a method. We can change the method implementation dynamically at run-time, only thing we need to follow doing so would be to maintain the parameter type & return type.

For example: If I declare delegate with return type int & two parameters as string and int respectively, all the references which are set using this delegate should follow this signature.

internal class Program
   {
       protected delegate int tempFunctionPointer(string strParameter, int intParamater);

       public static void Main()
       {
           DelegateSample tempObj = new DelegateSample();
           tempFunctionPointer funcPointer = tempObj.FirstTestFunction;
           funcPointer("hello", 1);
           Console.ReadKey();
           funcPointer = tempObj.SecondTestFunction;
           funcPointer("hello", 1);
           Console.ReadKey();
       }
   }

   public class Employee
   {
       public string Name { get; set; }
       public int Age { get; set; }
   }

   public class XEmployee
   {
       public string Name { get; set; }
       public int Age { get; set; }

       public bool IsExEmployee {
           get { return true; }
       }
   }

  public class DelegateSample
   {
       public int FirstTestFunction(string strParameter, int intParamater)
       {
           Console.WriteLine("First Test Function Execution");
           Console.WriteLine(strParameter);
           return intParamater;
       }

       public int SecondTestFunction(string strParameter, int intParamater)
       {
           Console.WriteLine("Second Test Function Execution");
           Console.WriteLine(strParameter);
           return intParamater;
       }

       public void ThirdTestFunction(string strParameter, int intParamater)
       {
           Console.WriteLine("Third Test Function Execution");
           Console.WriteLine(strParameter);
       }

       public bool FourthTestFunction(Employee employee)
       {
           return employee.Age < 27;
       }

       public XEmployee FifthTestFunction(Employee employee)
       {
           return new XEmployee() {Name = employee.Name, Age = employee.Age};
       }

       public int SixTestFunction(Employee strParameter1, Employee strParamater2)
       {
           return strParameter1.Name.CompareTo(strParamater2.Name);
       }
   }

Delegates can be executed synchronous or asynchronously. Code sample mentioned above is an example of synchronous processing. To make it an Asynchronous process, we need to use BeginInvoke method.

funcPointer.BeginInvoke("Hello", 1, null, null); 

First two parameters are the inputs for the function. 3rd parameter can be set for getting call back after execution of process. Detailed explanation of making Asynchronous call is available here.

When Do I Use Delegate?

Looking at the sample above, a lot of us might think this can be also achieved using Interface or abstract class, then why do we need delegate.

Delegate can be used in the following scenarios:

  1. If you don’t want to pass your interface or abstract class dependence to internal class or layers.
  2. If the code doesn't need access to any other attributes or method of the class from which logic needs to be processed.
  3. Event driven implementation needs to be done.

Different Flavors of Delegate

As .NET Framework evolved over a period of time, new flavors have been added to keep implementation simple & optimized. By default, you get all the features & functionality with flavors which you get with delegate. Let’s have a look at Func delegate.

Func<TParameter, TOutput>

Func is logically similar to base delegate implementation. The difference is in the way we declare. At the time of declaration, we need to provide the signature parameter & its return type.

Func<string, int, int> tempFuncPointer;

First two parameters are the method input parameters. 3rd parameter (always the last parameter) is the out parameter which should be the output return type of the method.

Func<string, int, int> tempFuncPointer = tempObj.FirstTestFunction;
int value = tempFuncPointer("hello", 3);
Console.ReadKey();

Func is always used when you have return object or type from method. If you have void method, you should be using Action.

Action<TParameter>

Action is used when we do not have any return type from method. Method with void signature is being used with Action delegate.

Action<string, int> tempActionPointer; 

Similar to Func delegate, the first two parameters are the method input parameters. Since we do not have return object or type, all the parameters are considered as input parameters.

Action<string, int> tempActionPointer = tempObj.ThirdTestFunction;
tempActionPointer("hello", 4);
Console.ReadKey();  

Predicate<in T>

Predicate is a function pointer for method which returns boolean value. They are commonly used for iterating a collection or to verify if the value does already exist. Declaration for the same looks like this:

Predicate<Employee> tempPredicatePointer;  

For sample, I have created an Array which holds a list of Employees. Predicate is used to get employee below age of 27:

Predicate<Employee> tempPredicatePointer = tempObj.FourthTestFunction;
Employee[] lstEmployee = (new Employee[]
{
   new Employee(){ Name = "Ashwin", Age = 31},
   new Employee(){ Name = "Akil", Age = 25},
   new Employee(){ Name = "Amit", Age = 28},
   new Employee(){ Name = "Ajay", Age = 29},
});

Employee tempEmployee = Array.Find(lstEmployee, tempPredicatePointer);
Console.WriteLine("Person below 27 age :" + tempEmployee.Name);
Console.ReadKey();

<pre lang="cs">//Code block which gets executed while iteration 
public bool FourthTestFunction(Employee employee)
{
   return employee.Age < 27;
}  

Converter<TInput, TOutput>

Convertor delegate is used when you need to migrate / convert one collection into another by using some algorithm. Object A gets converted into Object B.

Converter<Employee, XEmployee> tempConvertorPointer 
                = new Converter<Employee, XEmployee>(tempObj.FifthTestFunction); 

For sample, I have created XEmployee entity. All the Employees in the collection get migrated to XEmployee Entity.

 Employee[] lstEmployee = (new Employee[]
            {
                new Employee(){ Name = "Ashwin", Age = 31},
                new Employee(){ Name = "Akil", Age = 25},
                new Employee(){ Name = "Amit", Age = 28},
                new Employee(){ Name = "Ajay", Age = 29},
            });

Converter<Employee, XEmployee> tempConvertorPointer 
                = new Converter<Employee, XEmployee>(tempObj.FifthTestFunction);

XEmployee[] xEmployee = Array.ConvertAll(lstEmployee, tempConvertorPointer);
Console.ReadKey(); 

//Code block which get executed while iteration 
 public XEmployee FifthTestFunction(Employee employee)
 {
    return new XEmployee() {Name = employee.Name, Age = employee.Age};
 } 

Comparison<T>

Comparison delegate is used to sort or order the data inside a collection. It takes two parameters as generic input type and return type should always be int. This is how we can declare Comparison delegate.

Comparison<string> tempComparison = new Comparison<string>(tempObj.SixTestFunction); 

In this sample, Employee Name is used to Sort the order. All the entity inside the collection will be processed using SixthTestFunction which contains the logic for processing / sorting the data as per our requirement.

Comparison<Employee> tempComparisonPointer
                = new Comparison<Employee>(tempObj.SixTestFunction);
            Array.Sort(lstEmployee, tempComparisonPointer);
            Console.ReadKey();

 public int SixTestFunction(Employee strParameter1, Employee strParamater2)
        {
            return strParameter1.Name.CompareTo(strParamater2.Name);
        }

Points of Interest

Using the new delegates, we can achieve better level of abstraction & performance can also been gained by avoiding unnecessary iteration or conversion logic. All three delegates (Predicate, Converter, Comparison) do have optimized internal logic for iteration.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Ashwin. Shetty
Architect STC
India India
I have 12+ years of experience in Microsoft Technology. My complete profile is available at http://www.linkedin.com/in/ashwinshetty

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun29-May-14 22:30
memberHumayun Kabir Mamun29-May-14 22:30 
GeneralMy vote of 3 Pin
Samer Abu Rabie23-Mar-14 20:59
memberSamer Abu Rabie23-Mar-14 20:59 
GeneralMy vote of 3 Pin
Paulo Zemek19-Mar-14 8:31
professionalPaulo Zemek19-Mar-14 8:31 
QuestionRe: My vote of 3 Pin
Ashwin. Shetty19-Mar-14 8:57
memberAshwin. Shetty19-Mar-14 8:57 
AnswerRe: My vote of 3 Pin
Paulo Zemek19-Mar-14 9:16
professionalPaulo Zemek19-Mar-14 9:16 
QuestionA delegate is more than a pointer to a method. Pin
Paulo Zemek19-Mar-14 4:46
professionalPaulo Zemek19-Mar-14 4:46 
QuestionVery nice article Pin
Marv Anderson17-Mar-14 10:40
memberMarv Anderson17-Mar-14 10:40 
SuggestionSome really good examples missing Pin
AndyVGa12-Mar-14 9:38
professionalAndyVGa12-Mar-14 9:38 
AnswerRe: Some really good examples missing Pin
Ashwin. Shetty13-Mar-14 19:15
memberAshwin. Shetty13-Mar-14 19:15 
GeneralRe: Some really good examples missing Pin
AndyVGa14-Mar-14 6:18
professionalAndyVGa14-Mar-14 6:18 
AnswerRe: Some really good examples missing Pin
Ashwin. Shetty15-Mar-14 5:24
memberAshwin. Shetty15-Mar-14 5:24 
GeneralRe: Some really good examples missing Pin
David Pierson18-Mar-14 13:17
memberDavid Pierson18-Mar-14 13:17 
GeneralRe: Some really good examples missing Pin
AndyVGa8-Apr-14 7:44
professionalAndyVGa8-Apr-14 7:44 
GeneralMy vote of 5 Pin
RogerGlez12-Mar-14 7:51
memberRogerGlez12-Mar-14 7:51 
GeneralRe: My vote of 5 Pin
Ashwin. Shetty12-Mar-14 7:53
memberAshwin. Shetty12-Mar-14 7:53 
General"Modern" flavors... Pin
dctpt11-Mar-14 3:42
memberdctpt11-Mar-14 3:42 
GeneralMy vote of 5 Pin
JF GODILLON10-Mar-14 23:01
professionalJF GODILLON10-Mar-14 23:01 
GeneralMy vote of 5 Pin
shizung10-Mar-14 19:44
membershizung10-Mar-14 19:44 
BugThis is not quite right Pin
Matt T Heffron10-Mar-14 10:28
professionalMatt T Heffron10-Mar-14 10:28 
AnswerRe: This is not quite right Pin
Ashwin. Shetty10-Mar-14 17:56
memberAshwin. Shetty10-Mar-14 17:56 
GeneralRe: This is not quite right Pin
Andreas Gieriet14-Mar-14 0:12
professionalAndreas Gieriet14-Mar-14 0:12 
GeneralRe: This is not quite right Pin
Paulo Zemek19-Mar-14 8:25
professionalPaulo Zemek19-Mar-14 8:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150819.1 | Last Updated 10 Mar 2014
Article Copyright 2014 by Ashwin. Shetty
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid