April 24th, 2008

Interesting Extension Hack To Get Around NullReferenceException’s

Today I came across an interesting extension pattern that I didn’t know how the runtime would react. Normally when you do something like the following:

string s = null;
Console.WriteLine(s.Trim()); // throws NullReferenceException

You get a NullReferenceException meaning that you didn’t first check to see if the object was null before trying to call one of its methods. This is pretty common and results in patterns that usually look like this:

string s = null;
string result = null;

if (s != null)
    result = s.Trim();

Console.WriteLine(result);

This results in a ton of extra code to just verify you inputs. It’s a dirty task but somebody has to do it. So today it occurred to me that maybe extension methods were my answer to this code bloat. To better understand extension method, Scott Hanselman has done a great job explaining how they function and what they look like to the CLR.

So I whipped up the following console application and tested my theory out.

public static class Extension
{
    public static string TryTrim(this string s)
    {
        if (s == null)
            return s;

        return s.Trim();
    }
}

class Program
{
    static void Main(string[] args)
    {
        string s = null;
        Console.WriteLine(s.TryTrim());  // notice that I don't have the code bloat like above
    }
}

This works without a NullReferenceException because the code actually looks like this to the compiler.

public static class Extension
{
    public static string TryTrim(string s)
    {
        if (s == null)
            return s;

        return s.Trim();
    }
}

class Program
{
    static void Main(string[] args)
    {
        string s = null;
        Console.WriteLine(TryTrim(s));  // this is how the run time sees the code
    }
}

So with this new understanding of extension methods you don’t have to worry about checking if a variable is null or not before trying to use an extension method. The more I use extension methods the more I love them.

Tags: , ,

Social: kick it on DotNetKicks.com | Bookmark | View blog reactions

This entry was posted on Thursday, April 24th, 2008 at 10:19 am and is filed under C#, Programming. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

9 Responses to “Interesting Extension Hack To Get Around NullReferenceException’s”

  1. Will Says:

    That is awesome. I wondered what would happen in these cases. I’m starting to use extension methods more and more to ease common coding tasks. I’m glad to see I can refactor my null checks into the extension methods themselves. Now if we can only get extension properties so I can ditch the ()’s…

  2. Nick Berardi Says:

    You use to be able to hack your own properties in to classes so that you could change the visibility of them, but this was back in 1.0 and they corrected it in 1.1 and then introduced visibility to the properties in 2.0. However I wonder would would happen in this case.

    public static void set_MyProperty(this string s)…

    If it compiled you should be able to do:
    string s = “”;
    s.MyProperty = value;

    However there seems to be a whole host of problems with making property extensions that is not currently dealt with in the .NET framework yet.

    How would you set the value inside the object the get_ and set_ methods are static and outside of the object. Where would you store this value, because remember the property is static and any property thing you would set would be the same across all properties for that method. Which would become confusing since it looks like a property of the object.

    I am sure they will work it out, but probably not till 4.0 or 4.5.

  3. Andemann Says:

    Why not just extend the entire string object to return string.Emtpy if the value is null?

    Your tryTrim should return string.empty and not the input value when the input value is null, that way you’ll avoid a nullreferenceexception when you attempt to use the trimmed value

  4. Erik Says:

    @Nick: “Where would you store this value” - I’ve seen some extension method “properties” use this pattern:

    private static Dictionary _Tags = new Dictionary();

    public static void set_Tag(this object taggedObject, object tag)
    {
    if(taggedObject == null) return;
    if(_Tags.ContainsKey(taggedObject) && tag == null) _Tags.Remove(taggedObject);
    _Tags[taggedObject] = tag;
    }

    public static object get_Tag(this object taggedObject)
    {
    if(!_Tags.ContainsKey(taggedObject)) return null;
    return _Tags[taggedObject];
    }

    Of course this solution doesn’t take into account objects that go out of scope; memory leaks will occur, although WeakReference could help here. This still doesn’t get you property syntax in 3.5, even though it looks like it should.

    ps: I hope the indentations work…

  5. Reflective Perspective - Chris Alcock » The Morning Brew #81 Says:

    [...] Interesting Extension Hack To Get Around NullReferenceException’s - Nick Berardi shows an interesting use of extension methods to help work round problems with te code bloat associated with checking nuls before you call methods. [...]

  6. Alvin Ashcraft Says:

    Good idea for a handy extension method. How about this tweak to your ‘if’ condition:

    if (String.IsNullOrEmpty(s))
    return s;

    Just a thought to save a Trim() operation if the string is already empty.

    Thanks!

  7. Nick Berardi Says:

    Alvin,
    You are right, I really didn’t optimize my code, it was more for an example.

    Erik,
    That is pretty proprietary from the standpoint that the compiler would have to generate a dictionary to just hold the property if it was integrated into the language.

    Andemann,
    That is not quite how extension methods work. NULL is an absence of an object, so you wouldn’t be able to tell the object to response with String.Empty since the object isn’t really there.

  8. Dew Drop - April 25, 2008 | Alvin Ashcraft's Morning Dew Says:

    [...] Interesting Extension Hack to Get Around NullReferenceExceptions (Nick Berardi) [...]

  9. Nick Berardi Says:

    I am glad to see everybody is enjoying this.

Leave a Reply