Delegates in C#


Delegates – it’s a type that holds the reference of method in an object. It’s also called type safe (It ensure that operation is working on right kind of data) function pointer.
Adv –    Encapsulating the method call from caller
                Effective use of delegate improve the performance
                Use to call method asynchronously.
                Declare Delegate ->Public Delegate int delegate_name(Param optional)
                Multicast Delegate – holds the reference of more than one method. Must contain the methods return void.
How to use
                Single Delegate
 private  delegate void d_Print(string strPrint);
        private delegate int d_Add(int fNum, int sNum);
        static void Main(string[] args)
        {
            //Simple Use of Delegate
            d_Print print = PrintString;
            print("Hello");

            //Pass Delegate as parameter
            PrintHelper(PrintString, "Hello");

            //Delegate With return value
            d_Add add = AddTwoNumbers;
            Console.Write(add(4, 5));
        }
        private static void PrintString(string strPrint)
        {
            Console.Write(strPrint);
        }
        //Pass delegate as parameter
        private static void PrintHelper(d_Print dP, string strPrint)
        {
            dP(strPrint);
        }
        //Add two numbers
        private static int AddTwoNumbers(int num1, int num2)
        { return num1 + num2; }
Multicast Delegate
 private delegate int d_ArithmeticOpr(int fNum, int sNum);
        static void Main(string[] args)
        {
            //Use of multicast Delegate
            d_ArithmeticOpr math = new d_ArithmeticOpr(AddTwoNumbers);
            //Add Subtract Method to delegate object
            math += new d_ArithmeticOpr(SubtractNumber);
            //This call will do both Addition and Subtraction
            Console.Write(math(20, 10));

            //remove Add call from delegate
            math -= new d_ArithmeticOpr(AddTwoNumbers);
            //This call only do the Subtraction
            Console.Write(math(20, 10));
        }
        //Subtract Two Numbers
        private static int SubtractNumber(int num1, int num2)
        {
            return (num1-num2);
        }
        //Add two numbers
        private static int AddTwoNumbers(int num1, int num2)
        { return num1 + num2; }

Comments

Popular posts from this blog

SSIS Merge Join - Both inputs of the transformation must contain at least one sorted column, and those columns must have matching metadata SSIS

jsGrid

Add Item to SharePoint List with attachment using client object model