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.