Tuesday, March 9, 2010

Basics of Delegates

Delegate


     Delegates are of 2 types.

            • Simple Delegate
            • Multicast Delegate

Simple Delegate

     A delegate is a form of type-safe function pointer that represents a method with a specific signature and return type.


Multicast Delegates:
     Multicast delegate is nothing but a delegate that points to multiple methods.

             Syntax (C#)
             [Access Modifier] delegate [ret-type] del_name(parameter-list);


     Method is not an object but it always has a physical allocation in the memory. This address is the entry point for the method and it is called when the method is invoked. In delegate, address of the method can be assigned to a delegate object. Using the same delegate object different methods can be called by changing the reference of methods. Advantage of delegate is that it allows user to invoke a method at runtime, not at compile time.

For example, calculator is like a delegate who calls multiple methods for addition, subtraction, multiplication and division. It means one objects calls multiple methods which is at runtime, not in compile time.


     Let’s go with a simple program to explain about delegate. Create a C# console application and inside the application create a class “Calculator”





    class Calculator
    {
        public int Add(int num1, int num2)
        {
            return num1 + num2;
        }

        public int Sub(int num1, int num2)
        {
            return num1 - num2;
        }
    }


     On next step declare the delegate object on “Program” class and call the 2 methods from "Calculator" class using the delegate object.





    class Program
    {
        public delegate int DelegateCalc(int x,int y);
        static void Main(string[] args)
        {
            int num1 = 32;
            int num2 = 25;

            Calculator calc = new Calculator();           

            //Addition
            DelegateCalc delCalc = new DelegateCalc(calc.Add);
            Console.WriteLine("Result(Add):" + delCalc(num1, num2));

            //Subtraction
            delCalc = new DelegateCalc(calc.Sub);
            Console.WriteLine("Result(Sub):" + delCalc(num1, num2));
            Console.ReadKey();
        }
    }


    Result







In general, delegates are useful for two main reasons.

     • Delegates support events.
     • Delegates give your program a way to execute a method at runtime without having to know precisely what that method is at compile time.