Search content within the blog

Tuesday, April 21, 2009

Delegates and events in C# - Part II

Types of Delegate

Delegates are of two types:
Single cast delegate

A delegate is called single cast delegate if it invokes a single method. In other words we can say that SingleCast Delegates refer to a single method with matching signature. SingleCast Delegates derive from the System.Delegate class

SingleCast Delegates can be defined using the following syntax:

public delegate int mydelegatename(int param1, int param2);

Note : parameters are optional

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
{
delegate int AddDelgate(int num1, int num2); //declaring the delegate
protected void Page_Load(object sender, EventArgs e)
{
AddDelgate objAddDel = new AddDelgate(Add); //instansiate it
Response.Write("Result:" + objAddDel(2, 3).ToString() + "<br>");
}
}

public int Add(int num1, int num2)
{
return (num1 + num2);
}

Output would be as follows:
Result:5

Next add one more method called max which returns maximum of two numbers as follows

public int Max(int num1, int num2)
{
if (num1 > num2)
{
return num1;
}
else
{
return num2;
}
}

continue to add these lines in page load
AddDelgate objmaxNumber = new AddDelgate(Max);
Response.Write("MaxNumber between 2 and 3:" + objmaxNumber(2, 3).ToString() + "<br>");

Now the result will be
Result:5
MaxNumber between 2 and 3:3

Use of cobine and remove
continue to add these lines in page load
Response.Write("combined delegate example <br>");
AddDelgate objSumdelegate = null;
objSumdelegate = (AddDelgate)System.Delegate.Combine(objAddDel, objmaxNumber);
Response.Write(objSumdelegate(2, 3).ToString()+"<br>");
Response.Write("remove delegate example :<br>");
objSumdelegate = (AddDelgate)System.Delegate.Remove(objSumdelegate, objmaxNumber);
Response.Write("After removing the result of addition is :<br>");
Response.Write(objSumdelegate(2, 3).ToString() + "<br>");


Now the reult will be
Result:5
MaxNumber between 2 and 3:3
combined delegate example
3
remove delegate example :
After removing the result of addition is :
5

No comments:

Post a Comment