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. namespace Delegates.Samples.Demo
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. Action<string> log = new Action<string>(LogInfo);
  9. log.Invoke("Hi ALL");
  10. Console.ReadLine();
  11. }
  12. static void LogInfo(string message)
  13. {
  14. Console.WriteLine(message);
  15. }
  16. }
  17. }
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. namespace Delegates.Samples.Demo
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. Func<int, int, int> addFunc = new Func<int, int, int>(Add);
  9. int result = addFunc(3, 4);
  10. Console.WriteLine(result);
  11. Console.ReadLine();
  12. }
  13. static int Add(int a, int b)
  14. {
  15. return a + b;
  16. }
  17. }
  18. }
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. namespace Delegates.Samples.Demo
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. Predicate<int> IsEven = new Predicate<int>(IsEvenNumber);
  9. Console.WriteLine(IsEven(10));
  10. Console.WriteLine(IsEven(1567));
  11. Console.ReadLine();
  12. }
  13. static bool IsEvenNumber(int number)
  14. {
  15. return number % 2 == 0;
  16. }
  17. }
  18. }
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.