Social Icons

twitter google plus linkedin rss feed



Extension Methods for Null Objects

Is it possible to use an extension method on something that is null?

How beautiful would it be to do something like:
if (!MyString.IsNull()) return MyString.ToString();
I read somewhere a couple of years ago that would be impossible because if the object was null you’d not be allowed to call the method or something like that… But in my head it makes perfect sense.

So I have been refraining myself of doing this for a long time but today I felt brave enough.

The Method Extensions:
public static bool IsNull(this string str)
    return str == null;

public static string ToStringSafe(this object obj)
    return (obj ?? string.Empty).ToString();
The main method obviously every good test program should be a console application:
static void Main(string[] args)
    string str = null;

    if (str.IsNull())
        Console.WriteLine("It was null...");
        Console.WriteLine("It wasn't null...");


And it works! This just opens a new dimension to my spaghetti recipes.

The first useful example that comes to my mind apart from the ToStringSafe and ToInt, ToDateTime... Look at me, I can't stop! is:

/// Disposes the object if it's not null.
public static void DisposeSafe(this IDisposable DisposableObject)
    if (DisposableObject != null)
With this method I won’t have to worry if the object is null or not. Everything is disposed properly!

It frightens me sometimes to get so excited about this things…