开发者

String.IsNullOrEmpty() Check for Space

What is needed to make String.IsNullOrEmpty() count whitespa开发者_运维百科ce strings as empty?

Eg. I want the following to return true instead of the usual false:

String.IsNullOrEmpty(" ");

Is there a better approach than:

 String.IsNullOrEmpty(" ".Trim());

(Note that the original question asked what the return would be normally hence the unsympathetic comments, this has been replaced with a more sensible question).


.NET 4.0 will introduce the method String.IsNullOrWhiteSpace. Until then you'll need to use Trim if you want to deal with white space strings the same way you deal with empty strings.

For code not using .NET 4.0, a helper method to check for null or empty or whitespace strings can be implemented like this:

public static bool IsNullOrWhiteSpace(string value)
{
    if (String.IsNullOrEmpty(value))
    {
        return true;
    }

    return String.IsNullOrEmpty(value.Trim());
}

The String.IsNullOrEmpty will not perform any trimming and will just check if the string is a null reference or an empty string.


String.IsNullOrEmpty(" ")

...Returns False

String foo = null;
String.IsNullOrEmpty( foo.Trim())

...Throws an exception as foo is Null.

String.IsNullOrEmpty( foo ) || foo.Trim() == String.Empty

...Returns true

Of course, you could implement it as an extension function:

static class StringExtensions
{
    public static bool IsNullOrWhiteSpace(this string value)
    {
        return (String.IsNullOrEmpty(value) || String.IsNullOrEmpty(value.Trim()));
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜