In my last post I showed how easy it is to add syntax sugar with extension methods. But that’s not all – even though from the call site the extension method looks like any other, it is a different beast altogether. This is obvious from the signature of the extension method – we are explicitly expecting the reference to the object of the extended class as the first parameter, unlike with the regular methods where this reference is implicit. If that’s really the case, what happens if you call using null reference? Assuming you check for null, this should work, right? It does! Here’s an (admittedly contrived) example:
using System;
using System.Linq;

public class Foo {
  public int Bar = 2;
}

public static class Extensions {
  public static bool IsTwo(this Foo foo) {
    return null != foo && 2 == foo.Bar;
  }
}

public static class Program {
  public static void Check(Foo foo) {
   Console.WriteLine(string.Format("The foo {0} two", foo.IsTwo() ? "is" : "is not"));
  }
  
  public static void Main() {
    Foo foo1 = new Foo();
    Check(foo1);
    Foo foo2 = null;
    Check(foo2);
  }
}
If the IsTwo was regular method, calling foo.IsTwo for the second time would be using the null reference foo2, and we would get a null reference exception. Instead, the output of this little program is:
The foo is two
The foo is not two

Use with caution.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
0 Comments