Search This Blog

2010/01/17

How to use delegates to create an event

     An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object. The most familiar use for events is in graphical user interfaces; typically, the classes that represent controls in the interface have events that are notified when the user does something to the control (for example, click a button).

Events, however, need not be used only for graphical interfaces. Events provide a generally useful way for objects to signal state changes that may be useful to clients of that object. Events are an important building block for creating classes that can be reused in a large number of different programs.

Events are declared using delegates. A delegate object encapsulates a method so that it can be called anonymously. An event is a way for a class to allow clients to give it delegates to methods that should be called when the event occurs. When the event occurs, the delegate(s) given to it by its clients are invoked.


public class WaterTank
    {

        public delegate void TankOverFlow(string str);
        public event TankOverFlow TankFlow;
        int Maxsize;
        int Size;
        string TankName;

        //default constructor
        public WaterTank()
        {
            TankName = "MyTank";
            Maxsize = 1000;
            Size = 0;
        }

        //parametrized constructor
        public WaterTank(string Name, int MaxSz)
        {
            TankName = Name;
            Maxsize = MaxSz;
            Size = 0;
            TankFlow = TankFlow + new TankOverFlow(TestHandler);
        }



        //Event Handler
        public void TestHandler(string str)
        {
            MessageBox.Show(str + "-Tank Overflow Handled By Native Class");
        }

        //Method That  will eventually trigger event

        public void AddWater(int x)
        {
            Size = Size + x;
            if (Size > Maxsize)
            {
                //Raise an Event Tank is overFlowing
                TankFlow("Tank is OverFlowing");
            }
        }
    }

Now we will create a new window form that will demonstrate use of the created event where interface will define a new tank of our choice and fill it with water of particular quantity.





 public partial class Form1 : Form
{
WaterTank obj;
public Form1()
{
InitializeComponent();
}
public void obj_TankFlow(string TankName)
{
MessageBox.Show(TankName + "-Tank Overflow Handled By Calling Class");
}
private void BtnCreateTank_Click(object sender, EventArgs e)
{
string str = TxtTankName.Text;
int mxsize = Convert.ToInt16(TxtTankCapacity.Text);
obj = new WaterTank(str, mxsize);

//obj is created here handler should be here
obj.TankFlow += new WaterTank.TankOverFlow(obj_TankFlow);

MessageBox.Show("Tank Name=" + str + " ;Tank Size=" + mxsize);
TxtName.Text = str;
TxtLevel.Text = "0";
TxtCapcity.Text = mxsize.ToString();

}
private void BtnAddWater_Click(object sender, EventArgs e)
{
int sz;
sz = Convert.ToInt16(TxtTankAdd.Text);
obj.AddWater(sz);
TxtLevel.Text = sz.ToString();
}

}

when we go on filling the tank with water at one point the Tank get full and then  the WaterTank class raise an event TankFlow.As the event has been handled in both caller and native class both message will come one after another first from native class then from calling class

No comments:

Post a Comment