.NET built-in function that combines String.IsNullOrEmpty and String.IsNullOrWhiteSpace [closed]
Is there a built-in function in .NET that combines both String.IsNullOrEmpty and String.IsNullorWhiteSpace?
I can easily write my own, but my question is why isn't there a String.IsNullOrEmptyOrWhiteSpace function?
Does the String.IsNullOrEmpty trim the string first? Perhaps a better question is, Does String.Empty qualify as white space?
why isn't there a String.IsNullOrEmptyOrWhiteSpace
That function is called string.IsNullOrWhiteSpace
:
Indicates whether a specified string is null, empty, or consists only of white-space characters.
Shouldn’t that have been obvious?
Yes, the String.IsNullOrWhiteSpace
method.
It checks if a string is null, empty, or contains only white space characters, so it includes what the String.IsNullOrEmpty
method does.
String.IsNullOrWhiteSpace does check for null, Empty or WhiteSpace.
These methods do effectively Trim the string before doing the test so " " will return true.
Here is the decompiled method using dotPeek.
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public static bool IsNullOrEmpty(string value)
{
if (value != null)
return value.Length == 0;
else
return true;
}
/// <summary>
/// Indicates whether a specified string is null, empty, or consists only of white-space characters.
/// </summary>
///
/// <returns>
/// true if the <paramref name="value"/> parameter is null or <see cref="F:System.String.Empty"/>, or if <paramref name="value"/> consists exclusively of white-space characters.
/// </returns>
/// <param name="value">The string to test.</param>
public static bool IsNullOrWhiteSpace(string value)
{
if (value == null)
return true;
for (int index = 0; index < value.Length; ++index)
{
if (!char.IsWhiteSpace(value[index]))
return false;
}
return true;
}
精彩评论