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