One key feature of C# as a language is its event support. While the basic infrastructure has remained substantially unchanged from the original 1.0 version of C#, the supporting syntax has become progressively cleaner and clearer.
In the recently released C# 3.0, lambda expressions coupled with enhanced type inference give the simplest syntax yet.
Let’s start at the beginning, and see how things have changed over time.
In C# 1.0, hooking up a method to be called when a button is pressed looked something like this:
Note how we needed to explicitly create an EventHandler object to wrap the method before registering for the event.
C# 2.0 made this a little simpler by having the compiler automatically insert the construction of the Event Handler where it was needed:
In fact, anonymous methods allow us to get rid of the supporting method altogether:
Though, doing this means that we can’t easy deregister the event later if needed. But, often we don’t need to do this.
Since Lambda Expressions provide an equivalent, more compact syntax, we can restate this:
As you can see, using a lambda expression in this way to register for an event is both concise and simple. Type inference makes everything work sweetly in Visual Studio, and the expression gains access to local variables as required.
On the down side, deregistration of the event isn’t possible (as no reference to the lambda expression is retained), and the unusual construct may be a minor hurdle for future maintenance by inexperienced developers.
Purely as a matter of style, I’ve found that spreading the event registration over two lines is easier to read than compressing the whole thing onto one. Your milage may vary, of course.