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)</span>`.

If only C# would support extension properties

Tags:

Updated:

Comments

Leave a Comment

Your email address will not be published. Required fields are marked *

Loading...