Wednesday 10 February 2016

Difference between Delegate, Func, Action and Predicate.

Lets first see what is delegate.

If you will say delegate always one thing is come into our mind, a function pointer calling as an argument.
But it’s no sense with this Definition its showing the concept of use of delegate it won’t say why we need it and when we need this delegate.
For this we need to check with the English meaning of delegate, a representative. e.g Indian delegate go to US to deal something.
So this representative will give the time to time details of the operation and this delegate is the wrapper for our India which we hide but to present to the US also.




So the below things come us into find if delegate.
a.       Communication
b.      Callback
c.       Wrapper for Operation.(Abstraction  and Encapsulation)
d.      Publish and subscription model

To work with delegate we need to follow as:
Declare à Create à Point à Invoke'

Declare Delegate:
public delegate string  GetEmployee(int empId,string empName);

Create & Point in delegate :
 GetEmployee obj = new GetEmployee(CreateEmployee);

Invoke delegate:
obj(1, "Satya Delegate")


What is difference between Delegate, Func, Action and Predicate.

Func : it is delegate for a function which will may or may not take the argument  and return a value.
Action : it is delegate for a function which may or may not take parametrs and doesnot returen value.
Predicate : It is specialized version of Func that take an argument eveluate a value againt some criteria and always return as bool value.


How to use all this in your application the syntax for it as;
public delegate string  GetEmployee(int empId,string empName);

        static void Main(string[] args)
        {

            GetEmployee obj = new GetEmployee(CreateEmployee);
            Console.WriteLine(obj(1, "Satya Delegate"));
            /// Example of function
            Func<int, string, string> ShowEmp = new Func<int, string, string>(CreateEmployee);
            Console.WriteLine(CreateEmployee(1, "Satya Func"));

            /// Action
            Action<int, string> oAct = new Action<int, string>(NewEmployee);
            oAct(2, "prakash");

            /// Predicate
            Predicate<int> oPred = new Predicate<int>(IsEmplyeeExist);
            Console.WriteLine(oPred(1));

          
        }


private static bool IsEmplyeeExist(int obj)
        {
            return true;
        }

        private static void NewEmployee(int id, string Name)
        {
            Console.WriteLine(String.Format("New User ID " + id + " User Name : " + Name));
        }

        public static string CreateEmployee(int id, string Name)
        {
            return String.Format("User ID " + id + " User Name : " + Name);

        }

No comments:

Post a Comment