views:

72

answers:

4

I have a method called isStringOnlyWhitespace():

public static bool isStringOnlyWhitespace(string toEval)
{
    string stringNoWhitespace = Regex.Replace(toEval, @"\s", "");
    if (stringNoWhitespace.Length > 0) return false;
    else return true;
}

Is there any reason to use this method to check for blank/null strings over String.IsNullOrEmpty()?

+10  A: 

Sure, if you are shooting for slower code that is harder to read :)

You really want to use string.IsNullOrWhitespace though. Whoever wrote that code might have done so before this method existed. But even still, I'd prefer myString.Trim().Length == 0 in that case.

Matt Greer
`string.IsNullOrWhitespace` was introduced with .NET 4.0, so older versions can only use `string.IsNullOrEmpty`.
Oded
Thanks Oded, I forgot it's new. I edited my answer to reflect that.
Matt Greer
+1, minor gripe. I would much rather just hand code IsNullOrWhitespace than do an allocation. The method is fairly straight forward to code up.
JaredPar
This would be the correct answer if I was using .net 4.0. +1.
Matthew Jones
+2  A: 

The method you give doesn't handle nulls whereas String.IsNullOrEmpty does.

That would indicate to me that passing your method a null value is an error condition which is different behavior from String.IsNullOrEmpty.

Also, as others have pointed out, your method would return true for isStringOnlyWhitespace(" ") whereas String.IsNullOrEmpty(" ") would return false.

Justin Niessner
+1  A: 

Yes. Strings containing only whitespace are not considered to be empty. isStringOnlyWhitespace(" ") returns true, but string.IsNullOrEmpty(" ") returns false.

recursive
A: 

No ;)

a) I think since .net 4 you can use string.IsNullOrWhitespace

b) try something like

public static bool IsStringOnlyWhitespace(this string str)
{
    // if you want to check for null:
    return str == null || string.IsNullOrEmpty(str.Trim());
    // else
    return string.IsNullOrEmpty(string.Trim());
}
Zebi
you mean str.Trim()? And even if you do, that doesn't handle nulls like IsNullOrEmpty
recursive
corrected the code, thanks for the hit.The method I proposed either handles null or does not handle null, depending on the statement you pick.
Zebi