Saturday 7 August 2021

delegate vs Func vs Predicate

 

A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.


Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates. You create a custom method, and a class such as a windows control can call your method when a certain event occurs. The following example shows a delegate declaration:

Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.


Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).


Predicate is a special kind of Func often used for comparisons.


Though widely used with Linq, Action and Func are concepts logically independent of Linq. C++ already contained the basic concept in form of typed function pointers.


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;  

        }  

    }  

}  


=====================================

Predicate


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;  

        }  

    }  

}   

No comments:

Post a Comment