5.9 Packaging Event Arguments

 <  Day Day Up  >  

You want to package state information into a class that you can use as arguments to an event handler.

Technique

Create a new class derived from System.EventArgs . Add any public member variables to the class that the event handler can then access. The event delegate should use this class as a parameter in its parameter list. When the event is fired , create an instance of this class, ensuring that its member variables have been properly set to reflect the current event information:

 
 public class MenuItemEventArgs : EventArgs {     public int id;     public string displayString;     public MenuItemEventArgs( int id, string displayString )     {         this.id = id;         this.displayString = displayString;     } } 

Comments

Packaging event arguments into a class derived from EventArgs , believe it or not, is purely for aesthetic reasons. If you look at the EventArgs class, you'll see that it doesn't add any additional functionality beyond the methods and properties contained in System.Object . That said, you are free to forego this procedure of argument-packing altogether and simply pass parameters normally when you fire an event. However, it is recommended, just as coding and naming guidelines are recommended, that you create a consistent method for event arguments by using the steps shown here.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net