14

I continuously check string fields to check if they are null or blank.

if(myString == null || myString.Trim().Length == 0)
{
    throw new ArgumentException("Blank strings cannot be handled.");
}

To save myself a bit of typing is it possible to create an extension method for the String class that would have the same effect? I understand how extension methods can be added for a class instance but what about adding a static extension method to a class?

if(String.IsNullOrBlank(myString))
{
    throw new ArgumentException("Blank strings cannot be handled.");
}
sipsorcery
  • 30,273
  • 24
  • 104
  • 155

10 Answers10

36

You could do:

public static bool IsNullOrBlank(this String text)
{
  return text==null || text.Trim().Length==0;
}

And then call it like this:

if(myString.IsNullOrBlank())
{
  throw new ArgumentException("Blank strings cannot be handled.");
}

This works because C# allows you to call extension method on null instances.

Ðаn
  • 10,934
  • 11
  • 59
  • 95
Sean
  • 60,939
  • 11
  • 97
  • 136
  • 1
    Interestingly, C# doesn't allow you to call a method with a null instance as it emits a callvirt IL instruction. However, in IL if you make a call via the "call" instruction you can call on a null instance. – Sean Mar 16 '09 at 07:57
  • 13
    @dan - I don't think that a method that implies a null check in its name is a bad use for extension methods. – Maslow Aug 08 '09 at 13:12
  • @Maslow - agreed. C# allows extension methods on null objects, so use it. – dlchambers Mar 08 '12 at 13:06
  • You can throw a NullReferenceException from an extension method to simulate the behavior of an instance method if the this argument is null, but provide a more descriptive error message than "Object reference not set to the instance of an object." – FishBasketGordo Nov 13 '14 at 17:50
17

I know this is an old question but since it was bumped and it hasn't been mentioned already, as of .NET 4.0 you can simply use the String.IsNullOrWhiteSpace method to achieve the same result.

Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174
  • 1
    String.IsNullOrWhiteSpace is a static method, extension is more convinient to use. Even String.IsNullOrEmpty easier to use as Extension Method -see http://thomasfreudenberg.com/blog/archive/2008/01/25/string-isnullorempty-as-extension-method.aspx – Michael Freidgeim May 07 '12 at 07:25
6

You can safely use an extension method on the instance:

public static class StringExtensions
{
    public static bool IsNullOrBlank(this string s)
    {
        return s == null || s.Trim().Length == 0;
    }
}

Test cases:

string s = null;
Assert.IsTrue(s.IsNullOrBlank());
s = " ";
Assert.IsTrue(s.IsNullOrBlank());

It looks a bit weird though, and I would instead figure out why your strings need to be checked for this case so often. If you fix them at the source, you won't have to be so paranoid about them later!

Jim Arnold
  • 2,238
  • 14
  • 18
2

An overload to the existing answers could be:

public static bool IsNullOrBlank(this String text, Action<String> doWhat)
{
  if (text!=null && text.Trim().Length>0)
    doWhat(text);
}

Would be helpful if you only want to run code given a valid value.

Not a super useful example, but just showing the usage:

Name.IsNullOrBlank(name=>Console.WriteLine(name));
Ðаn
  • 10,934
  • 11
  • 59
  • 95
Maslow
  • 18,464
  • 20
  • 106
  • 193
2

Can you add static methods to existing classes? The answer is no, and the value would be pretty thin, because you'd still need to know which class name to type first; with extension methods, the advantage is that you start with a variable name and autocompletion shows you things that are applicable to it.

Another point often made is that extension methods should always throw an exception as soon as possible if their first argument is null. However, I think that rule is overkill if the method mentions in its name that it is designed to check for null.

The real problem you have is that you want to neatly and readably run some code after checking for a null reference. One way to capture that pattern is in my answer to this question.

Community
  • 1
  • 1
Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284
  • It's not the same, IsNullOrEmpty doesn't check for strings that contain only whitespace characters. – Joe Mar 15 '09 at 11:18
  • And also, if you call Trim() and the string was null, you will get a NullReferenceException. Sorry, not much of value in the answer and also misleading so -1. – erikkallen Mar 15 '09 at 11:24
  • The problem is you can't Trim till you check if it's null which is back to square one :(. Guess I could just create a new static class and call the method to that instead just would have been nice to have it on the String intellisense. – sipsorcery Mar 15 '09 at 11:26
  • I've removed that first part altogether, I agree it was misleading. – Daniel Earwicker Mar 15 '09 at 11:26
1

A bit late. But you can also put the code to throw an exception in an extension method too. I have two methods (for ArgumentNullException and NullReferenceException).

// strings
public static bool NullBlankCheck(this string s, string message = "",
    bool throwEx = true)
{
    return Check<NullReferenceException>(s.IsNullOrBlank(), throwEx, message);
}
public static bool NullBlankCheckArgument(this string s, string message = "",
    bool throwEx = true)
{
    return Check<ArgumentException>(s.IsNullOrBlank(), throwEx, message);
}

private static bool Check<T>(bool isNull, bool throwEx, string exceptionMessage)
    where T : Exception
{
    if (throwEx && isNull)
        throw Activator.CreateInstance(typeof(T), exceptionMessage) as Exception;
    return isNull;
}

public static bool IsNullOrBlank(this string s)
{
    return string.IsNullOrEmpty(s) || s.Trim().Length == 0;
}

nunit tests:

Assert.Throws<NullReferenceException>(() =>
{
    "".NullEmptyCheck();
});
Assert.Throws<ArgumentException>(() =>
{
    "".NullEmptyCheckArgument();
});

And then use it as:

public void Method(string someStr)
{
    someStr.NullBlankCheckArgument();
    // do something
    var str = someMethod();
    str.NullBlankCheck();
}
hIpPy
  • 4,649
  • 6
  • 51
  • 65
1

Although, this question was asked over a decade ago, I see no one has mentioned that there is a built in string method for handling this.

Therefore, please use string.IsNullOrWhitespace() instead. No hacking anything in, use the language feature and you're just fine.

Seun S. Lawal
  • 483
  • 6
  • 10
1
public static bool IsNullOrEmptyTrimmed(string value)
{
    return (value == null || value.Length == 0) ?
        true : value.Trim().Length == 0;
}

or

public static bool IsNullOrEmpty(this String value, bool checkTrimmed)
{
    var b = String.IsNullOrEmpty(value);
    return checkTrimmed ? (b && value.Trim().Length > 0) : b;
}
Ðаn
  • 10,934
  • 11
  • 59
  • 95
abatishchev
  • 98,240
  • 88
  • 296
  • 433
0

With a few tricks, you make it look like you've added to the String class in any one cs file:

namespace JDanielSmith
{
    public static class String
    {
        public static bool IsNullOrBlank(string text)
        {
            return text == null || text.Trim().Length == 0;
        }
    }
}

(note, this is not an extension method, see my comment).

Then, in some other CS file:

using String = JDanielSmith.String;
namespace Foo.Bar.Baz
{
    class Program
    {
        static void test(string myString)
        {
            if (String.IsNullOrBlank(myString))
            {
                throw new ArgumentException("Blank strings cannot be handled.");
            }
        }
...

Notice the "desired" syntax of String.IsNullOrBlank(). I'm not necessarily suggesting that you actually do things this way, just pointing out how you could set things up to make your code work.

Ðаn
  • 10,934
  • 11
  • 59
  • 95
  • That introduces massive name confusion. Now coders will have to double check whether that String is a JDanielSmith.String or a System.String... ugh! – code4life Mar 14 '11 at 17:34
  • The extension method described above is clearly more understandable. @code4life is right: Ugh! – dlchambers Mar 08 '12 at 13:04
-1
public static bool IsNull(this object o)
{
    return string.IsNullOrEmpty(o.ToStr());
}

public static bool IsNotNull(this object o)
{
    return !string.IsNullOrEmpty(o.ToStr());
}

public static string ToStr(this object o)
{
    return o + "";
}
Ðаn
  • 10,934
  • 11
  • 59
  • 95
omoto
  • 1,212
  • 1
  • 17
  • 24
  • I don't think I like this very much. The semantics of IsNull and IsNotNull are surprising. Why do you add the string.Empty to o in ToStr? – Greg D Mar 15 '09 at 16:42
  • It's more useful for objects(for example when need to do something with Eval("blalblabla")), but for strings could be used too. Why you don't like this? – omoto Mar 15 '09 at 21:21
  • Conceptually, (o == null) != (o.ToStr == string.empty). If I want to test a reference for null, I'm better off just testing it for null. (I'm not your downvote, just saying that I think I understand why it happened.) – Greg D Mar 16 '09 at 12:04