Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.IsNullOrEmpty() Check for Space

Tags:

c#

What is needed to make String.IsNullOrEmpty() count whitespace 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).

like image 294
Asim Sajjad Avatar asked Mar 31 '10 11:03

Asim Sajjad


People also ask

How do I check if a string contains whitespace?

Use the test() method to check if a string contains whitespace, e.g. /\s/. test(str) . The test method will return true if the string contains at least one whitespace character and false otherwise.

Does IsNullOrWhiteSpace check for empty string?

IsNullOrWhitespace(string value) returns true if the string is null, empty, or contains only whitespace characters such as a space or tab.

Is null or white space?

The IsNullOrWhiteSpace method interprets any character that returns a value of true when it is passed to the Char. IsWhiteSpace method as a white-space character.

What does string IsNullOrEmpty return?

The C# IsNullOrEmpty() method is used to check whether the specified string is null or an Empty string. It returns a boolean value either true or false.


2 Answers

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

like image 59
João Angelo Avatar answered Oct 16 '22 11:10

João Angelo


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()));
    }
}
like image 21
Rowland Shaw Avatar answered Oct 16 '22 10:10

Rowland Shaw