Monday, July 21, 2008

Extension Methods - Cool

Since the first release of the .NET Framework (2002), Microsoft as significantly improved the quality and features of the framework. Also, the compilers and the Visual Studio have evolved in a fantastic way.

One of the many features introduced in VS2008 (with the new compilers) was the Extension Methods. What are they? A cute little thing! Ok, technically speaking, I prefer to quote Scott Gu:

“Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type. Extension Methods help blend the flexibility of “duck typing” support popular within dynamic languages today with the performance and compile-time validation of strongly-typed languages. Extension Methods enable a variety of useful scenarios, and help make possible the really powerful LINQ query framework that is being introduced with .NET as part of the “Orcas” release.”

But what’s happening behind the scene? Is this complicated? Well, lets start by looking at the extension methods with one example from Scott Gu. Have you ever wanted to check if a string is in some way valid? For example, have you ever wanted to check if a string is a valid e-mail address or “postal code”? Before extension methods, you’d probably write something like this:

(click to enlarge)

As you can see, there’s a static class with static methods to validate the string, which is passed as a parameter. But we’re trying to check if a string is in some way valid, so, shouldn’t we have this capability on the string type? Well, this is Extension Methods. Here’s the version using extension methods:

(click to enlarge)

Cool! You actually call a method from the string type! The “this” keyword tells the compiler that the extension method is to be applied to string type. However, what’s happening behind the scenes? Well, if we compile both the examples we will notice that it’s the C# compiler that’s “doing the trick”. Here’s the IL for the first example:

(click to enlarge)

And here’s the IL for the second example using extension methods:

(click to enlarge)

As you may have noticed, the compiler actually transformed the extension method in a normal method call, generating a class. From the CLR point of view, everything is still the same (there’s one new flag).


This is “the big picture”. However, the extension methods can be used with every base class or interface. Basically, it can be applied to any type. And this is fantastic. The built-in LINQ Extension methods use this feature. Once you get used to some of these “syntactical sugar” improvements, you’ll get addicted.

There are so much new cool features with the new compilers that come with VS2008 that the best is to take a look at Scott Gus’ blog. Despite the fact that he normally doesn’t look at the generated IL, he discusses important issues and his speech is very easy to understand. It’s a fantastic source of information.

Wednesday, July 16, 2008

Memory Leaks

The .NET Framework evolves considerably from version to version. I think it’s the best software Microsoft has ever written and documented. The latest versions of the framework (and the compilers) are truly brilliant.

But not everyone works with the latest version. Some companies, for their own reasons, often work with older versions, some of them even with version 1.1. That was the case of some projects in my last job.

This introduction is just to contextualize why I’m talking about a “so old” version of the Framework. Remember the memory leaks in C++, when there was no Garbage Colector? Well, here’s one in .NET 1.x:


Tip: Upgrade! Always try to work with the latest version of the .NET Framework.

Wednesday, July 2, 2008

Be careful when using IIf

As I stated before, I’m a C# fan. The language itself is so beautiful that you can write clean and amazingly readable code. For example, recall the ternary expression:

(click to enlarge)

In the above example, we’re testing if the value that the variable “oneValue” contains equals “anotherValue”. If it does, CalculateSomething gets called. Otherwise, CalculateSomethingElse will be called. The result of one of these methods will be stored in the valueToPrint variable. This is the ternary expression.

Now, take a closer look at the CalculateSomethingElse method. As you can see, if we call this method an ArgumentException will be thrown, because we’re trying to convert a non-valid string to an integer. However, in the above example, the value in the “oneValue” variable equals the value in the “anotherValue” variable, so, the CalculateSomethingElse never gets called. If we run this application, everything will go as expected, with no Exceptions thrown:

(click to enlarge)

Now, VB.NET has something “similar”: the IIf. Take a look at the VB.NET version of the above example:

(click to enlarge)

The idea is basically the same as for the C# ternary expression. Remember that the CalculateSomethingElse method will throw an ArgumentException when called and the value in the “oneValue” variable equals the “anotherValue”. So, just like what happened with the C# example, you’d expect that everything would compile and run with no Exceptions (since the only method that should be called is the CalculateSomething because the test expression evaluates to true). However, this is not true. If you run the VB.NET example, you will get an ArgumentException:

(click to enlarge)

Why? Well, the IIf is actually a VB.NET function defined in the class Interaction (Microsoft.VisualBasic namespace). The problem with this is that at runtime, both the functions in the IIf get called. This is a major problem when you have large amount of work inside those methods or even something that might thrown an exception (e.g.: divide by zero). The IIf function is as follows:

(click to enlarge)


So, for those VB.NET users, the best is just to use IIf very carefully.

Tip: Compile both the examples and see the IL that was generated by the compilers.