Wednesday 27 July 2016

C Sharp Delegate

C# Delegate 

A delegate is a simple class that is used to point to methods with a specific signature, becoming essentially a type-safe function pointer.
If you have a C++ background then  thinking of them as function pointers is helpful
A delegate can be seen as a placeholder for a/some method(s).
By defining a delegate, you are saying to the user of your class 
"Please feel free to put any method that match this signature here and it will be called each time my delegate is called".
class Program
    {
        delegate int mathop(int n, int m);//funtion pointer
        public  static int sum(int a, int b)
        {
            return a + b;
        }
        public  static int multi(int a, int b)
        {
            return a * b;
        }

        static void Main(string[] args)
        {
            //direct call
            Console.WriteLine("\nCalling Sum  function normally and result is {0}", sum(11, 22));
            Console.WriteLine("\nCalling Multi function normally  and result is {0}", multi(11, 22));
            //call by delegate
            mathop ob = new mathop(sum);
            Console.WriteLine("\nCalling Sum  function by delegate  and result is {0}", ob(11, 22));
            ob = new mathop(multi);
            Console.WriteLine("\nCalling Multi  function by delegate  and result is {0}\n", ob(11, 22));
        }
    }

No comments:

Post a Comment