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).
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.
IsNullOrWhitespace(string value) returns true if the string is null, empty, or contains only whitespace characters such as a space or tab.
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.
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.
.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()));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With