String.IsNullOrBlank Extension Method

2019-02-06 05:59发布

问题:

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.");
}

回答1:

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.



回答2:

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.



回答3:

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!



回答4:

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.



回答5:

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));


回答6:

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();
}


回答7:

Bill Wagner in More Effective C# recommends against making extension functions work with null instances (pp. 183).

The reason is that extension methods are supposed to look like method calls, and you can't call a method with a null instance.



回答8:

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.



回答9:

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;
}


回答10:

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 + "";
    }