-1

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?

Nick
  • 1,417
  • 1
  • 14
  • 21

4 Answers4

13

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?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
0

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.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

String.IsNullOrWhiteSpace does check for null, Empty or WhiteSpace.

These methods do effectively Trim the string before doing the test so " " will return true.

Mark Redman
  • 24,079
  • 20
  • 92
  • 147
0

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;
    }
aked
  • 5,625
  • 2
  • 28
  • 33