Delegates and Multicast Delegates

Posted by Raja under C# category on | Views : 3816
Delegates is a type which hold the reference of a method in an object.
Mutlicast delegate is a type which hold the reference of multiple methods in an object. In order to work with Mutlicast delegates, the method should return void, otherwise run-time error will throw.

Below is the code snippet of a CodeBehind aspx page, simply copy-paste this in code behind (below the namespace) and run.

public partial class _Default : System.Web.UI.Page
delegate int CalculateDelegate(int a, int b);
delegate void MutliCastDelegate(int a, int b);

protected void Page_Load(object sender, EventArgs e)
Response.Write("Delegates: ");
CalculateDelegate cDelegate = new CalculateDelegate(Add);

// call delegate
Response.Write(cDelegate(6, 9000).ToString());
Response.Write("<hr />");

Response.Write("Mutlicast Delegates: ");
MutliCastDelegate multi = new MutliCastDelegate(AddM);
multi += new MutliCastDelegate(Subtract);

// call multicast delegate
multi(50, 98999);
Response.Write("<hr />");

public void AddM(int a, int b)
Response.Write("Method 1: " + (a + b));

public void Subtract(int a, int b)
Response.Write("Method 2: " + (a - b));

private int Add(int a, int b)
return a + b;

Please let me know your feedback if any. Thank you.

Comments or Responses

Posted by: Deeraj on: 6/8/2010 Level:Starter | Status: [Member]
Also, the order of execution cannot be guaranteed and if one method throws exception, rest of the methods will not execute.

Posted by: Nisha.kaushik on: 4/6/2011 Level:Starter | Status: [Member] | Points: 10

I have implemented you above given code in our project but it is giving one error in the below line

multi += new MutliCastDelegate(Subtract);
Error-: Operand += can not be applied to operand of type System.Multicast delegate or _defaullt.multicastdelegate..I am using dot net 2008 with c#

Please help me out from this problem.


Login to post response