Tuesday, March 24, 2009

Event Handling

Second is that event keyword adds accessor method for the event which are just like properties for the fields. While properties have get and set, event accessors have add and remove.
An event is a message sent by an object to signal the occurence of an action.

EventHandler is a predefined delegate that specifically represents an event handler method for an event that does not generate data.

To respond to an event, we need to do 2 things:

(1) Create a method to respond to the event. It must return void and accept two parameters: and Object and an EventArgs(or a derived class):
(Represents an event with no event data.)

private void button1_Click(object sender, EventArgs e)
{
//Method Code
}

(2) Add the event handler to indicate which method should recieve events:
this.button1.Click+=new System.EventHandler(this.button1_Click);
//Here, Click is the predefined event handler.
//We can also define our own as:
//public event ButtonEventHandler ButtonClick;
//this.button1.ButtonClick +=
//new ButtonEventHandler(button1_Click);

Here Click is a predefined EventHandler. When the event occurs, the method you specified will run.

Note that we can define the data for event, instead of using EventArgs:

public class AlarmEventArgs : EventArgs
{
private readonly bool snoozePressed = false;
private readonly int nrings = 0;
// Constructor.
public AlarmEventArgs(bool snoozePressed, int nrings) {...}
// Properties.
public int NumRings{ get { return nrings;}}
public bool SnoozePressed { get { return snoozePressed;}}
public string AlarmText { get {...}}

}

And also we can write our own the EventHandler:

public delegate void AlarmEventHandler(object sender, AlarmEventArgs e);


The step of raise an event also has the following things:

(1) Create an event memeber:

public event AlarmEventHandler Alarm;

(2) Invoke the delegate within a method when you need to raise the event, as the following code demostrates:

AlarmEventArgs e =new AlarmEventArgs ();
if (Alarm != null)
{
//Invokes the delegates.
Alarm(this, e);
}
}

When we new an event memeber or handler, some people may ask why is it significant to use the keyworkd "event" here. It seems if we don't use key word event, like, public AlarmEventHandler Alarm; it also works, the reasons are below:

(1) Invoke restriction:
You don't want people to set the handler to be null and invoke your hander directly, see the blog here for explanation:
http://blog.voidnish.com/?p=20

(2)Event keyword allows the delegate declaration to be included in an interface specification unlike other fields and delegates which are not allowed.

(3)Event keyword adds accessor method for the event which are just like properties for the fields. While properties have get and set, event accessors have add and remove.

Another thing is that event handler can be built-in generic type:
eg:
EventHandler < MyEventArgs> temp = SampleEvent;
if (temp != null)
temp(null , new MyEventArgs(val));

No comments: