Section 12.4. Using Anonymous Methods


12.4. Using Anonymous Methods

In the previous example, you subscribed to the event by invoking a new instance of the delegate, passing in the name of a method that implements the event:

theClock.OnSecondChange +=   new Clock.SecondChangeHandler(TimeHasChanged);

You can also assign this delegate by writing the shortened version:

theClock.OnSecondChange += TimeHasChanged


Later in the code, you must define TimeHasChanged as a method that matches the signature of the SecondChangeHandler delegate:

public void TimeHasChanged(   object theClock, TimeInfoEventArgs ti) {   Console.WriteLine("Current Time: {0}:{1}:{2}",     ti.hour.ToString( ),      ti.minute.ToString( ),      ti.second.ToString( )); }

Anonymous methods allow you to pass a code block rather than the name of the method. This can make for more efficient and easier-to-maintain code, and the anonymous method has access to the variables in the scope in which they are defined:

clock.OnSecondChange += delegate( object theClock, TimeInfoEventArgs ti ) {   Console.WriteLine( "Current Time: {0}:{1}:{2}",   ti.hour.ToString( ),   ti.minute.ToString( ),   ti.second.ToString( ) ); };

Notice that instead of registering an instance of a delegate, you use the keyword delegate, followed by the parameters that would be passed to your method, followed by the body of your method encased in braces and terminated by a semicolon.

This "method" has no name, hence it is anonymous . You can invoke the method only through the delegate; but that is exactly what you want.



Programming C#(c) Building. NET Applications with C#
Programming C#: Building .NET Applications with C#
ISBN: 0596006993
EAN: 2147483647
Year: 2003
Pages: 180
Authors: Jesse Liberty

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