View Single Post
Old Oct 3rd, 2005, 7:17 PM   #2
Dameon
Troll
 
Dameon's Avatar
 
Join Date: Apr 2005
Location: Texas
Posts: 730
Rep Power: 4 Dameon is on a distinguished road
I'll try to break it down.

1. An event is more or less a list of delegates. When you raise an event, all the event handlers (which are delegates) are invoked.

2. A delegate is like a function prototype. In the case of events, it specifies what parameters the event handlers take.

An example is if you had an AlarmClock class, which happens to be an example in the MSDN.

3. Your alarm clock would have an Alarm event, an AlarmEventHandler delegate, and an AlarmEventArgs class, following the typical .Net pattern (though you don't have to).

4. The Alarm class has an OnAlarm method that allows subclasses to both raise (subclasses can't call the event directly) and handle (overriding is cleaner than an event) the Alarm event. Note that AlarmEventHandler says that any handlers have to have a sender parameter (a reference to who raised the event, since a single handler often serves many objects) and a paramter of type AlarmEventArgs (derived from EventArgs and containing data specific to an Alarm event).

When you want to add a handler on the alarm:
Alarm anAlarm = new Alarm();
anAlarm.Alarm += new AlarmEventHandler(myHandler); //Adds a delegate pointing to myHandler, which matches the prototype for AlarmEventHandler

When the Alarm needs to go off (called from inside Alarm)
OnAlarm(new AlarmEventArgs(<insert stuff relevant data>);

Inside OnAlarm:
if (Alarm != null)  //An event can be null. We don't want an exception.
   Alarm(this, theEventArgsParameter); //Passes the sender and event args.

Your Handler called myHandler (Which matches the AlarmEventHandler delegate):
MessageBox.Show("Alarm has gone off!");

Now, take a look at the examples for events provided by MSDN and see if you can understand what's going on. Then, create a project with a form (A Windows Application in Visual Studio), and see what the form designer adds when you tell it to add an event handler.

If you have specific questions, seeing how broad Events are, please elaborate.

As for when to use them: Whenever an event occurs (surprised?) that one or more parts of your code needs to be made aware of, but the originator of the event doesn't know who wants to know about it. Look at a Button control. Does the button know what parts of your code to call when it is clicked? No. A perfect canidate for an event, which is why there is a Click event on a Button.
__________________
MD5(sig) = bcef75433db02e9ad9bf81d6f7c5c270
Dameon is offline   Reply With Quote