5.7 Declaring Events

 <  Day Day Up  >  

You want to create an event within your class.


Technique

First, create a delegate that is used for the event, as shown in the previous recipe. Next , create a member variable of the type within your class placing the keyword event after the variable's access modifier:

 
 class ConsoleMenu {     public delegate void MenuEventHandler( object sender, string[] args );     public event MenuEventHandler OnMenuEvent; } 

Comments

Delegates allow flexibility within a program that otherwise wouldn't be available, or at least would be difficult to implement, to alter the flow of control dynamically while an application is running. Because delegates provide an inherent connection between two disparate objects, it seems only natural to utilize this design when creating an event infrastructure, which is exactly the case with the .NET Framework.

The first step in the process to add events to your object is to give the event you want to fire a name and to declare the method signature for that event. You declare the method signature for an event using a delegate. In the previous recipe, you saw that a delegate is simply a method declaration using the delegate keyword. Furthermore, because a delegate is bound to a different implementation, it does not contain an implementation of its own, which means there is no method body associated with that method. A delegate associated with an event is used as the event handler for the object that has requested to be notified for that event. The process of requesting notification or subscribing to an event is covered in the next recipe.

Events have an associated name to distinguish them from the actual delegates they are bound to. You declare events by creating a member variable within your class whose data type is that of the delegate to which it is bound. Unlike with regular variables , however, you must use the event keyword to allow special processing by the compiler. When you do so, the compiler generates additional information, in IL, which creates the necessary information to control how that event is connected to handlers and how the event is fired . Just like the delegate keyword, the event keyword generates a nested class. However, this class is private and is used internally by methods that the compiler has also emitted . Listing 5.4 shows the code used in this and the following two recipes. The class that supports events is ConsoleMenu , and as you can guess by the name, it supports a console-based menu system, albeit somewhat rudimentary. The event fired is OnMenuEvent , which is bound to the MenuEventHandler delegate.

Listing 5.4 ConsoleMenu Class Fires the OnMenuEvent Event
 using System; using System.Collections; namespace _7_AddingEvents {     class Class1     {         static void Main(string[] args)         {         }     }     class ConsoleMenu     {        ArrayList menuItems = new ArrayList();         bool quitMenu = false;         // menu item event handler delegate         public delegate void MenuEventHandler( object sender, string[] args );         // event fired when user selects a menu item         public event MenuEventHandler OnMenuEvent;         // adds a menu item to the internal ArrayList         public void AddMenuItem( string text )         {             menuItems.Add( text );         }         public void QuitMenu()         {             quitMenu = true;         }         public void DisplayMenu()         {             string input;             do             {                 int idx = 1;                 int choice = 0;                 // display each menu item string prefaced by its index value                 foreach( string menuChoice in menuItems )                     Console.WriteLine( "{0}: {1}", idx++, menuChoice );                 Console.Write( "Enter choice: " );                 // get users input and convert to integer                 input = Console.ReadLine();                 choice = Int32.Parse( input[0].ToString() );                 if( choice > 0 && choice <= menuItems.Count )                 {                     // build event arguments                     string[] args = new string[2];                     args[0] = input[0].ToString();                     args[1] =                       menuItems[Int32.Parse(input[0].ToString())-1].ToString();                     // fire event to be handled by client using this class                     OnMenuEvent( this, args);                 }                 else                 {                     Console.WriteLine( "Invalid choice!\n" );                 }             } while ( quitMenu == false );             quitMenu = false;         }     } } 

You can add new menu items by using the AddMenuItem method, which uses a string as the name of the menu item when it is displayed. To display the menu and accept user input, you use the DisplayInput method. This method continually loops until the quitMenu private variable is set to true . The actual firing of the event occurs after the user has entered her input value and after that value is validated .

Firing an event is slightly different from the method used to call a delegate method. When you used a delegate, you could simply call it like any other method, and the runtime would invoke the actual method implementation it was bound to. However, the event itself is just a variable and not an actual method even though the preceding code uses a method-calling syntax. To fire an event, use the event name as the method name, but use the parameter list of the delegate that the event is bound to. In this case, the event name OnMenuEvent is the method name, and the parameter data types are those of the MenuEventHandler delegate. Once you call it, any clients that have subscribed to that event will be notified.

 <  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