Developer Geeks Home

Multicast Delegates in .Net

RSS
 

  • Posted one year ago
  • Category: .Net Framework, C#, Generics,
  • Audiences: Architect, Developer, System Analyst,

This article will introduce you to the multicast delegate in .net and will explain how to use multicast delegate, using sample code in c#.

Multicast Delegates can hold and invoke multiple methods. In this example, we declare a simple delegate called MyDelegateMethod, which can hold and then invoke the MyMethod1 and MyMethod2 methods sequentially.

The += method creates a new delegate by adding the right delegate operand to the left delegate operand.

Example:

using System;

delegate void MyDelegateMethod( ); 

class MyDelegateSample
{
	static void Main( )
	{
		new MyDelegateSample( ); // Invoke delegate methods
	} 

	MyDelegateSample( ) 
	{
		MyDelegateMethod myMethod = null;
		myMethod += new MyDelegateMethod(MyMethod1);
		myMethod += new MyDelegateMethod(MyMethod2);
		myMethod ( );
	} 

	void MyMethod1( ) 
	{
		Console.WriteLine("In MyMethod1...");
	} 

	void MyMethod2( ) 
	{
		Console.WriteLine("In MyMethod2...");
	}
} 

A delegate can also be removed from another delegate using the -= operator.

Example:

MyDelegateSample( ) 
{
	MyDelegateMethod myMethod = null;
	myMethod += new MyDelegateMethod(MyMethod1);
	myMethod -= new MyDelegateMethod(MyMethod1);
	myMethod ( ); // myMethod is now null, hence throws NullReferenceException
} 

Delegates are invoked in the order they are added. If a delegate has a non-void return type, then the value of the last delegate invoked is returned.

Note that the += and -= operations on a delegate are not thread-safe. 

comments powered by Developer Geeks

My Recent Articles [86]