IsNull Extension Method

I'm strongly considering adopting the use of an IsNull extension method in my .NET 3.5 coding projects.  A quick search to see what others have to say about this revealed a new web site dedicated to extension methods, which includes this IsNull method ready to go:

public static bool IsNull(this object source)
{
  return source == null;
}

The String class supports the IsNullOrEmpty() method now, but you have to pass it your instance yourself.  This is another good candidate for Extension Method treatment.  Brad Wilson posted about this earlier this year, and received some good comments, none of which seem to indicate that these are evil or icky.

From the ExtensionMethod.Net site, here is an example of the String check that I use so frequently:

public static bool IsNotNullOrEmpty(this string input) {
    return !String.IsNullOrEmpty(input);
}

There are actually quite a few cool ones for strings.  I think I like having Format as an extension as well:

using System;
using System.Linq
 
public static class StringExtensions
{
    public static string Format(this string format, object arg, params object[] additionalArgs)
    {
        if (additionalArgs == null || additionalArgs.Length == 0)
        {
            return string.Format(format, arg);
        }
        else
        {
            return string.Format(format, new object[] { arg }.Concat(additionalArgs).ToArray());
        }
    }
}

Update: The Format extension method doesn't work as-is.  I've renamed mine to Formatx(), which works.

blog comments powered by Disqus