6.8. Delegates and Anonymous Methods

As part of Visual Studio 2005, C# 2.0 added support for anonymous methods. This new language feature is particularly useful when it comes to implementing delegate methods. Instead of requiring you to write separate, standalone methods for each delegate, anonymous methods allow you to employ a "shorthand" technique where the delegate's implementation and the consumer of that delegate are declared in tandem.

Here's a simple example that declares a method that requires a delegate and the anonymous method that implements that delegate all in one pass:

[C# code]
collCustList.Sort(delegate(Customer cust1, Customer cust2) {
    return Comparer<Customer>.Default.Compare(cust1, cust2);
});

In this example, you have a generic list that contains customers and you want to sort this list using the list's Sort() method, which accepts a Comparer delegate. Instead of declaring a method that conforms to the Comparer signature, you've simply declared an anonymous method that implements the delegate as part of the call. This method will get created and supplied to the Sort() method all in one, semishort bit of text. In some respects, this improves the readability and maintainability of your code in that it marries the delegate implementation directly to the method using it. It should be very clear, as you read this, how the comparison is going to be performed. If this weren't an anonymous method, you would have to determine what delegate implementation was supplied ...

Get Professional .NET 2.0 Generics 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.