Is there any reason to use this Regex method over String.IsNullOrEmpty()?
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开发者_Python百科 true;
}
Is there any reason to use this method to check for blank/null strings over String.IsNullOrEmpty()?
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.
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.
Yes. Strings containing only whitespace are not considered to be empty. isStringOnlyWhitespace(" ")
returns true, but string.IsNullOrEmpty(" ")
returns false.
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());
}
精彩评论