Of all the new features in C# 3.0, Lambda expressions have to be one of my favourites.
One non-obvious way that they can be used is as event handlers, in just the way that anonymous delegates could be.
Consider these examples, handling the AfterExpand method of a WinForms TreeView.
Original code, from the era of C# 2.0:
First, lets swap out the delegate for a lambda expression:
The C# compiler is willing to infer the new TreeViewEventHandler(), so we can leave it out:
Now, the types of the arguments to the lamda expression can be inferred:
Simple, clean and easy to read … well, once you’re used to it, anyway.
Comments
blog comments powered by Disqus