Saturday, December 4, 2010

Working with Delegates in C#

What are delegates and why are they required?



Delegates are function pointers in C# that are managed and type safe and can refer to one or more methods that have identical signatures. Delegates in C# are reference types. They are type safe, managed function pointers in C# that can be used to invoke a method that the delegate refers to. The signature of the delegate should be the same as the signature of the method to which it refers. According to MSDN, "A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure."

C# provides support for Delegates through the class called Delegate in the System namespace. Delegates are of two types.

· Single-cast delegates

· Multi-cast delegates

A Single-cast delegate is one that can refer to a single method whereas a Multi-cast delegate can refer to and eventually fire off multiple methods that have the same signature.

The signature of a delegate type comprises are the following.

· The name of the delegate

· The arguments that the delegate would accept as parameters

· The return type of the delegate

A delegate is either public or internal if no specifier is included in its signature. Further, you should instantiate a delegate prior to using the same.

The following is an example of how a delegate is declared.

Declaring a delegate

public delegate void TestDelegate(string message);


The return type of the delegate shown in the above example is "void" and it accepts a string argument. Note that the keyword "delegate" identifies the above declaration as a delegate to a method. This delegate can refer to and eventually invoke a method that can accept a string argument and has a return type of void, i.e., it does not return any value. You can use a delegate to make it refer to and invoke a method that has identical signature as the delegate only. Even if you are using multi-cast delegates, remember that you can use your delegate to refer to and then fire off multiple methods that have identical signatures only.

A delegate should always be instantiated before it is used. The following statement shows how you can instantiate a delegate.

Instantiating a delegate

TestDelegate t = new TestDelegate(Display);


Implementing Delegates in C#
This section illustrates how we can implement and use delegates in C#. The following is an example of a delegate that is used to refer to a method of identical signature as the delegate and eventually invoke the method using the delegate.


using System;
using System.Data;
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 Header : System.Web.UI.UserControl
{
public event ColorChangedEventHandler ColorChanged;
public event LinkClickEventHandler Clicked;
string _texts;
string _text;
public void Page_Init(object sender, EventArgs e)
{
//Wire-up the EventHandler
this.colorList.SelectedIndexChanged += new System.EventHandler(Index_Changed);
if (_texts.IndexOf('$') > 0)
{
string[] Texts = _texts.Split('$');
LinkButton lnk;
Label lbl;
for(int cnt = 0; cnt < Texts.Length; cnt++)
{
lnk = new LinkButton();
lnk.Text = Texts[cnt];
lnk.Click += new EventHandler(lnk_Click);
plc.Controls.Add(lnk);
lbl = new Label();
lbl.Text = "";
plc.Controls.Add(lbl);
}
}
}
public string Text
{
set
{
_text = value;
}
get
{
return _text;
}
}

void lnk_Click(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
_text = lb.Text;
if (Clicked != null)
{
//Call the Delegate and pass the ColorEventArgs
Clicked(this, e);
}
}
//Method called when the DropDownList value changes
public void Index_Changed(object sender, EventArgs e)
{
//Create a new Arguments Object
ColorEventArgs myArgs = new ColorEventArgs();
//Get the color selected
myArgs.Color =colorList.SelectedItem.Text;
colorList.BackColor = System.Drawing.Color.Blue;
//Check if any method has subscribed for notification
//If you don't do this then an exception gets thrown
//When there are no methods subscribing to the Event
if(ColorChanged!=null)
{
//Call the Delegate and pass the ColorEventArgs
ColorChanged(this, myArgs);
}
}
public string Texts
{
get
{
return _texts;
}
set
{
_texts = value;
}
}
}

public delegate void AddClickEventHandler(object sender,EventArgs e);
//Define a Delegate
public delegate void LinkClickEventHandler(object sender,EventArgs e);
//Define a Delegate
public delegate void ColorChangedEventHandler(object sender, ColorEventArgs e);
//Define a Class that Extends the EventArgs

public class ColorEventArgs : System.EventArgs
{
private string color;
//Color Property
public string Color
{
get
{
return this.color;
}
set
{
this.color = value;
}
}
}
———————————————————————————————————————————————————
Using this in another page. Include the header.ascx file

protected void Page_Load(object sender, EventArgs e)
{
//attach functionality to the events in the header
Header1.ColorChanged += new ColorChangedEventHandler(Header1_ColorChanged);
Header1.Clicked += new LinkClickEventHandler(Header1_Clicked);
Database db = DatabaseFactory.CreateDatabase();
DataSet ds = db.ExecuteDataSet(CommandType.StoredProcedure, "usp_Employees");
}

void Header1_Clicked(object sender, EventArgs e)
{
Response.Write(Header1.Text);
}

void Header1_ColorChanged(object sender, ColorEventArgs e)
{
Response.Write("header color changed" + e.Color);
//throw new Exception("The method or operation is not implemented.");
}

No comments:

Post a Comment

PDF Arabic watermark using MVC and iTextSharp

PDF full page Arabic watermark using MVC and iTextSharp Download :  Source Code Most of the time we have requirement to  gen...