Tuesday, October 21, 2008

Extension Methods Don't Throw NullReferenceException!

Did you know that an extension method will not throw a NullReferenceException unless you explicitly tell it to? Because an extension method is technically not part of an instance of an object, they won't throw NullReferenceExceptions when the value from which they're called is null. Here's an example:


class ExtensionMethodTest

{

    public void Run()

    {

        string value = null;

        value = value.IfNull("Other");

        Console.WriteLine(value);

    }

}

 

static class StringExtensions

{

    public static string IfNull(this string value, string alternate)

    {

        if (String.IsNullOrEmpty(value))

            return alternate;

        return value;

    }

}


Add this to your code and call the Run() method. You'll notice that even though the variable value is null, it won't throw a NullReferenceException at runtime.