C# Extension Methods and IsNullOrEmpty

As Brad Wilson points out one of the nice features of C# 3.0′s extension methods is that they work on null instances. Indeed, why shouldn’t they? They’re just static methods that are invoked in a slightly different way. But this allows a subtle but very pleasing (to me this morning anyway) bit of syntactic sugar for the very commonly used String.IsNullOrEmpty() method.

So instead of:

if (string.IsNullOrEmpty(myString)) ...

you can have the more-readable:

if (myString.IsNullOrEmpty()) ...

by using:

public static class StringExtensions
{
   public static bool IsNullOrEmpty(this string str)
   {
      return string.IsNullOrEmpty(str);
   }
}

It’s a very small thing but I like it.

About these ads

4 Responses to C# Extension Methods and IsNullOrEmpty

  1. James says:

    JINX! http://blogs.ipona.com/dan/archive/2006/09/21/CSharp_30_Extension_Methods_Are_Great.aspx

    I’ve mellowed a little on extension methods since my comment on Dan’s post there, though…

    Actually, I’ve mellowed a lot. Extension methods rock.

  2. Dan says:

    Hmm, it seems I should wait for 18 months before showing James my ideas…..

  3. Chris says:

    I liked the extension example above. I tried to create a similiar one for NotEquals but it’s having some errors(An object reference is required for the non-static field, moth, or property ‘string.Equals(string)’
    My code:
    public static bool NotEquals(this string s)
    {
    return !string.Equals(s);
    }
    Any help would be greatly appreciated.

  4. duncansmart says:

    Chris, I guess you’d need 2 parameters, one to hold the ‘this’ reference (say ‘s1′), and one for the one you’re comparing against, e.g. ‘s2′:

    public static bool NotEquals(this string s1, string s2)
    {
    return !s1.Equals(s2);
    }

    You’d need to check for nulls also, but you get the idea.

Follow

Get every new post delivered to your Inbox.

Join 28 other followers

%d bloggers like this: