I’m sure that most of you know that you can’t call methods on a null reference, so you’ll expect that this code will fire a nasty exception:

IPath p = null;
int l = p.Length();

Except, it doesn’t.


In this case, Length() is an extension method:

public static int Length(this IPath path)

Instead of getting a NullReferenceException at the point of call, the Extension method is called normally with null as the parameter value. This is a side effect of the way that Extension methods are implemented, as static methods on static classes.

I’m dead sure this will prove useful - a way to write code that is less brittle, and which gives more useful diagnostics when a failure occurs.


blog comments powered by Disqus