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
Don't assume shared understanding  25 Jan 2026
Old blog posts, restored  26 Oct 2025
Better Table Tests in Go  21 Oct 2025
Error assertions  26 Apr 2025
Browsers and WSL  31 Mar 2024
Factory methods and functions  05 Mar 2023
Using Constructors  27 Feb 2023
An Inconvenient API  18 Feb 2023
Method Archetypes  11 Sep 2022
A bash puzzle, solved  02 Jul 2022
Archives
July 2008
2008