Thomas Freudenberg

Confessions of a caffeine addict

String.IsNullOrEmpty as Extension Method

Most you will probably know about Extension Method introduced with C# 3.0. If not, I strongly recommend to read ScottGu's explanation.

Anyway, a couple of days ago Brad Wilson posted an experiment:

What I wasn't sure was whether or not you could call these extension methods when you have a null instance of the object, since they're instance methods. The C++ guy in me said "sure, that should be legal", and the C# guy in me said "it's probably illegal, and that's too bad". Amazingly, the C++ guy in me won!

This code executes perfectly:

using System;

public static class MyExtensions {
    public static bool IsNull(this object @object) {
        return @object == null;
    }
}

public class MainClass {
    public static void Main() {
        object obj1 = new object();
        Console.WriteLine(obj1.IsNull());

        object obj2 = null;
        Console.WriteLine(obj2.IsNull());
    }
}

When you run it, it prints out "False" and "True". Excellent!

When I read that I immediatley thought of another application. I guess all my readers are familiar with String.IsNullOrEmpty which was introduced with .NET 2.0. So I asked myself if you can make IsNullOrEmpty a parameterless extension method:

using System;

public static class MyExtensions
{
    public static bool IsNullOrEmpty(this String s)
    {
        return String.IsNullOrEmpty(s);
    }
}

public class MainClass
{
    public static void Main()
    {
        string s1 = "Hello world";
        Console.WriteLine(s1.IsNullOrEmpty());

        string s2 = null;
        Console.WriteLine(s2.IsNullOrEmpty());
    }
}

Again, it prints out False and True. And in my opinion this syntactic sugar looks much more elegant than the ordinary String.IsNullOrEmpty(s2).

If only C# would support extension properties...

Comments

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# January 30, 2008 6:16 AM

WiredPrairie - C# Extension methods and strings … said:

Pingback from  WiredPrairie -   C# Extension methods and strings …

# September 3, 2008 5:45 PM

eKnacks said:

You've been knacked. Keep up the good work.

# December 10, 2008 8:56 PM

Wes said:

Seems like this could compile to something illegal depending on how you were using it.

# December 14, 2010 5:54 PM