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.

4 thoughts on “C# Extension Methods and IsNullOrEmpty

  1. 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.

  2. 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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s