जगदीश खोलिया: Delegate with example

Friday, December 14, 2012

Delegate with example

Delegate is a type which  holds the method(s) reference in an object. It is also referred to as a type safe function pointer.

Advantages

  • Encapsulating the method's call from caller
  • Effective use of delegate improves the performance of application
  • Used to call a method asynchronously

Declaration

public delegate type_of_delegate delegate_name()

Example:
public delegate int mydelegate(int delvar1,int delvar2)

Note

  • You can use delegates without parameters or with parameter list
  • You should follow the same syntax as in the method
    (If you are referring to the method with two int parameters and int return type, the delegate which you are declaring should be in the same format. This is why it is referred to as type safe function pointer.) 
 Sample program using delegate :

public delegate double Delegate_MyFirst(int Num1,int Num2);
class Class1
{
    static double AddVal(int val1,int val2)
    {
        return val1 + val2;
    }
    static void Main(string[] args)
    {
        //Creating the Delegate Instance
        Delegate_MyFirst Objdel = new Delegate_MyFirst(AddVal);
        Console.Write("Please Enter Values");
        int v1 = Int32.Parse(Console.ReadLine());
        int v2 = Int32.Parse(Console.ReadLine());
        //use delegate for processing
        double dblResult = Objdel(v1,v2);
        Console.WriteLine ("Result :"+dblResult);
        Console.ReadLine();
    }
}

Multicast Delegate

What is Multicast Delegate?

It is a delegate which holds the reference of more than one method.
Multicast delegates must contain only methods that return void, else there is a run-time exception.

Simple Program using Multicast Delegate

delegate void Delegate_Multicast(int x, int y);
Class Class2
{
    static void Method1(int x, int y)
    {
        Console.WriteLine("You r in Method 1");
    }

    static void Method2(int x, int y)
    {
        Console.WriteLine("You r in Method 2");
    }

    public static void Main()
    {
        Delegate_Multicast func = new Delegate_Multicast(Method1);
        func += new Delegate_Multicast(Method2);
        func(1,2);             // Method1 and Method2 are called
        func -= new Delegate_Multicast(Method1);
        func(2,3);             // Only Method2 is called
    }
}
 
Delegate is added using the += operator and removed 
using the -= operator.  

No comments: