String.IsNullOrEmpty() Check for Space

后端 未结 2 599
一个人的身影
一个人的身影 2020-12-31 03:23

What is needed to make String.IsNullOrEmpty() count whitespace strings as empty?

Eg. I want the following to return true instead of the usu

2条回答
  •  Happy的楠姐
    2020-12-31 03:50

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

提交回复
热议问题