Tuesday, February 8, 2011

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 "on" />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
}
}

Explanation

In the above example, you can see that two methods are defined named method1 and method2 which take two integer parameters and return type as void.
In the main method, the Delegate object is created using the following statement: 
Delegate_Multicast func = new Delegate_Multicast(Method1);
Then the Delegate is added using the += operator and removed using the -= operator.
 

No comments:

Post a Comment