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.

Why?

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.

Comments

blog comments powered by Disqus
Next Post
Mandelbrot Screensaver v3.1  14 Jul 2008
Prior Post
Dual Monitor Visual Studio  09 Jul 2008
Related Posts
Prefer declarative method names  03 Feb 2018
Using Premeditation  27 Jan 2018
With Relocation  20 Jan 2018
Using Consolidation  13 Jan 2018
Using Semantic Types  06 Jan 2018
Using Extension Methods  30 Dec 2017
Error Methods  25 Nov 2017
Pass implementations, not representations  14 Oct 2017
Avoiding the Singleton Pattern  22 Jul 2017
Implementing the Singleton Pattern  15 Jul 2017
More smart-code posts »
Related Pages
July 2008 archive