Using Anonymous Methods with Events


Anonymous methods are especially useful when working with events, because an anonymous method can serve as an event handler. This eliminates the need to declare a separate method, which can significantly streamline event-handling code. As explained, anonymous methods are a new feature added by C# 2.0.

Here is an example that uses an anonymous event handler:

 // Use an anonymous method as an event handler. using System; // Declare a delegate for an event. delegate void MyEventHandler(); // Declare an event class. class MyEvent {   public event MyEventHandler SomeEvent;      // This is called to fire the event.   public void OnSomeEvent() {     if(SomeEvent != null)       SomeEvent();   } } class AnonMethHandler {   public static void Main() {     MyEvent evt = new MyEvent();     // Use an anonymous method as an event handler.     evt.SomeEvent += delegate {       // This is the event handler.       Console.WriteLine("Event received.");     };     // Fire the event twice.     evt.OnSomeEvent();     evt.OnSomeEvent();   } }

The output is shown here:

 Event received. Event received.

In the program, pay special attention to the way the anonymous event handler is added to the event by the following code sequence:

 // Use an anonymous method as an event handler. evt.SomeEvent += delegate  {   // This is the event handler.   Console.WriteLine("Event received."); };

The syntax for using an anonymous event handler is the same as that for using an anonymous method with any other type of delegate.

Anonymous event handlers are especially useful because often the event handler is not called by any code other than the event handling mechanism. Thus, there is usually no reason for a stand-alone method. Because anonymous event handlers are a new feature, you will want to look for places to employ them when updating older, legacy code.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

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