06 Nov 2008

C# 3.0 allows adding new methods to existing types. These are called Extension Methods. This allow programmers to add methods to existing types, even if they are not partial or event sealed.

These special methods have to be declared in a special way:

  1. They must be declared within a static class
  2. They must be static
  3. The first parameter of the method has to be the type that is "extended", preceded by the this keyword

So, for example, let's copy the very useful IsNullOrEmpty method as an extension method.

public static class Extensions
    public static bool IsNullOrEmpty(this String s)
        return String.IsNullOrEmpty(s);

Simple. Calling this

String s = "";

returns true. You can even do


which returns true as well.

Now, all of this is actually an illusion. When the compilers finds


he will translates it in


So, when an extension method is used, there is one more parameter, that is of the type the extension method is defined on. In this case, String.

But, if it as parameter, it can be null, right? Yes!

String s = null;

or even

((String) null).IsNullOrEmpty()

will both work, without trowing a NullReferenceException.

Nothing revolutionary here, but I found funny to "call" method on a null object and not have an exception raised.

blog comments powered by Disqus