Anonymous Methods

In the preceding 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.SecondChanged +=
    new Clock.SecondChangeHandler(TimeHasChanged);

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

theClock.SecondChanged += 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,TimeInfoEventArgsti)
{
    Console.WriteLine("Current Time: {0}:{1}:{2}",
                       ti.Hour.ToString(  ),
                       ti.Minute.ToString(  ),
                       ti.=Second.ToString(  ));
}

C# offers anonymous methods that 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.SecondChanged += delegate( object theClock,TimeInfoEventArgs ti )
{
    Console.WriteLine( "Current Time: {0}:{1}:{2}",
                       ti.Hour.ToString(  ),
                       ti.Minute.ToString(  ),
                       ti.Second.ToString(  ) );
};

Warning

Overused, this can also make for cut-and-paste code that is harder to maintain.

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 ...

Get Programming C# 3.0, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.