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
Next Post
Mandelbrot Screensaver v3.1  14 Jul 2008
Prior Post
Dual Monitor Visual Studio  09 Jul 2008
Related Posts
Using Constructors  27 Feb 2023
An Inconvenient API  18 Feb 2023
Method Archetypes  11 Sep 2022
A bash puzzle, solved  02 Jul 2022
A bash puzzle  25 Jun 2022
Improve your troubleshooting by aggregating errors  11 Jun 2022
Improve your troubleshooting by wrapping errors  28 May 2022
Keep your promises  14 May 2022
When are you done?  18 Apr 2022
Fixing GitHub Authentication  28 Nov 2021
July 2008