Search content within the blog

Tuesday, April 21, 2009

Delegates and Events in c#- part III

You can refer previous to parts on the same topic for the basics

Multicast Delegates

MultiCast Delegates are nothing but a single delegate that can invoke multiple methods of matching signature. MultiCast Delegate derives from System.MulticastDelegate class which is a subclass of System.Delegate.

In Multi-Casting basically we create a single delegate that in turn invokes multiple encapsulated methods. We can use MultiCast Delegates when multiple calls to different methods are required. For example if we are required to call two methods on a single button click event or mouse over event then using MultiCast Delegates we can easily call the methods.

The System.MulticastDelegate class provides required methods to play with delegates. There are two methods, Combine and Remove, which are used to play with delegates.

The Combine method is a static method of System.MulticastDelegate class which is used to combine the delegates and the Remove method is used to remove the delegate from the list.

The example of combine and remove is presented in the previous here to view previous part

Multicast Example
Add a page called Events and Delegates.aspx in your code
Replicate your code- behind with the following

using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Events_and_Delegates_EandD : System.Web.UI.Page
//declare the following delegate
public delegate void PrintEmpnameDelegate(string empname);

protected void Page_Load(object sender, EventArgs e)
PrintEmpnameDelegate objPeintDel = null;
objPeintDel += new PrintEmpnameDelegate(PrintEmpName);
//or even the followinf is correct
// PrintEmpnameDelegate objPeintDel = new PrintEmpnameDelegate(PrintEmpName);
objPeintDel = null;
objPeintDel += new PrintEmpnameDelegate(PrintEmpNameSmall);


//Add the following methods

public void PrintEmpName(string empname)

public void PassEmpNameToPrint(PrintEmpnameDelegate objPrntDel)
if(objPrntDel!= null)
objPrntDel("Ashwin" + "<br>");

public void PrintEmpNameSmall(string empname)

//Output will be as follows

No comments:

Post a Comment