Delegates - Action vs Func vs Predicate

Introduction

 
As we know, a delegate is a pointer to a method. In this article, we will see 3 types of pointers, listed below:
  • Action
  • Func
  • Predicate

Action

 
Action is a delegate, it can be used to point a method that has no return type. (i.e. return type will be void.)
 
Below is the sample code of using an Action:
  1. using System;  
  2.   
  3. namespace Delegates.Samples.Demo  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Action<string> log = new Action<string>(LogInfo);  
  10.             log.Invoke("Hi ALL");  
  11.             Console.ReadLine();  
  12.   
  13.         }  
  14.   
  15.         static void LogInfo(string message)  
  16.         {  
  17.             Console.WriteLine(message);  
  18.         }  
  19.     }  
  20. }  
Below is the output snap of the Action delegate:
 
 
 

Func

 
Func is a delegate, we can define type(s) of input params, and at the end, we can write the output param type.
 
Below is the sample code of using Func:
  1. using System;  
  2.   
  3. namespace Delegates.Samples.Demo  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {   
  9.             Func<intintint> addFunc = new Func<intintint>(Add);  
  10.             int result = addFunc(3, 4);  
  11.             Console.WriteLine(result);  
  12.             Console.ReadLine();  
  13.   
  14.         }  
  15.         static int Add(int a, int b)  
  16.         {  
  17.             return a + b;  
  18.         }  
  19.     }  
  20. }  
Below is the output snap of the Func delegate:
 
 

Predicate

 
Predicate will always return bool, which accepts any type of parameter as its input.
 
Below is the sample code of using Func:
  1. using System;  
  2.   
  3. namespace Delegates.Samples.Demo  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Predicate<int> IsEven = new Predicate<int>(IsEvenNumber);  
  10.             Console.WriteLine(IsEven(10));  
  11.             Console.WriteLine(IsEven(1567));  
  12.             Console.ReadLine();  
  13.   
  14.         }  
  15.         static bool IsEvenNumber(int number)  
  16.         {  
  17.             return number % 2 == 0;  
  18.         }  
  19.     }  
  20. }   
Below is the output snap of the Predicate delegate:
 
 

Summary

 
In this article, we saw the usage of 3 types of delegates. For your reference, I uploaded the project file. You can download and check it out.


Similar Articles