String.IsNullOrBlank Extension Method

2019-02-06 05:28发布

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

10条回答
你好瞎i
2楼-- · 2019-02-06 05:52

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.

查看更多
Fickle 薄情
3楼-- · 2019-02-06 05:54

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楼-- · 2019-02-06 05:56
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;
}
查看更多
Juvenile、少年°
5楼-- · 2019-02-06 05:59

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.

查看更多
祖国的老花朵
6楼-- · 2019-02-06 06:01

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.

查看更多
萌系小妹纸
7楼-- · 2019-02-06 06:02

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();
}
查看更多
登录 后发表回答