Extension Methods with Null Object

I don’t use extension methods that much in the code, but they are very handy in several scenarious. Till yesterday, I didn’t know one important thing about their behavior with null objects.

Imagine following example; does it always throw NullReferenceException?

Person nobody = null;
nobody.GetTelephoneNumberExtension();

Well, duh…it’s so obvious. Or is it? Actually, there is one edge case when the NullReferenceException won’t be thrown and it’s when you use extension methods.

public static class PersonExtensions
{
    public static string GetTelephoneNumberExtension(this Person value)
    {
        if (value == null)
            return String.Empty;
        else
            ...
    }
}

Calling the extension method on an object doesn’t check for nullity and it’s the syntactic sugar for making a static call. It’s an important and a bit misleading difference between a normal and an extension method. I wouldn’t take an advantage of this behavior, but be aware of it.


Would you like to get the most interesting content about C# every Monday?
Sign up to C# Digest and stay up to date!