Monday, July 23, 2007

Fun with Anonymous Methods

A few years back when .NET 1.0 came out, I was presented with a choice: C# or VB? At the time, both languages shared all the same features; if you could do it in C#, you could do it in VB. Another cool thing with the advent of .NET was the fact that a VB assembly could reference a C# assembly (and vice-versa). So, having an extensive background in VB, I decided to stick with what I knew.

Fast-forward a few years. The languages have taken different paths, and with each new .NET release C# got 1 or 2 cool language features that VB didn't have. I kept sticking with my roots, however, and blindly forged ahead as a "VB guy".

This spring, however, I was thrown into the C# world and forced to swim. And you know what? I freakin' love it! I don't plan on ever going back; VB is old and busted, C# is the new hotness.

With all of that said, I've had some learning to do, and some catch-up to play. One of the features of C# that VB did not pick up was the use of anonymous methods. Even after learning about them, I still wasn't sure if I was keen on using them. There were pluses and minuses, and I couldn't decide which out-weighed the other, so I mostly shoved them into the back of my mind and forged ahead in other areas.

All this changed last week. I finally found a slam-dunk place to use anonymous methods: unit tests. By writing the method implementation in-line right into the unit test it can be more immediately clear what the test is doing. Here is a sample:

Don't worry too much about what the test is actually doing, but notice the highlighted part, which is attaching an anonymous method as an event handler. What I like about this is that it makes reading the unit test very clear. You don't have to jump to another function to see what exactly it is doing. I mean, even if you name it well, there is a chance it is not implemented correctly. Putting the implementation right into the test allows someone to easily verify the functionality without jumping around in the code.

1 comment:

Jeremy Wiebe said...

Not to keep you flip-flopping but the new VB.NET is going to have some nice features, one of which is language-native XML support. Although with things like extension methods and LINQ in C# (oops, just checked and VB will have LINQ too, it looks like), the new VB.NET will have a run for it's money!