string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

后端 未结 9 714
广开言路
广开言路 2020-11-28 03:02

Is use of string.IsNullOrEmpty(string) when checking a string considered as bad practice when there is string.IsNullOrWhiteSpace(string) in .NET 4.

相关标签:
9条回答
  • 2020-11-28 03:26

    Here is the actual implementation of both methods ( decompiled 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;
        }
    
    0 讨论(0)
  • 2020-11-28 03:32

    It says it all IsNullOrEmpty() does not include white spacing while IsNullOrWhiteSpace() does!

    IsNullOrEmpty() If string is:
    -Null
    -Empty

    IsNullOrWhiteSpace() If string is:
    -Null
    -Empty
    -Contains White Spaces Only

    0 讨论(0)
  • 2020-11-28 03:34

    string.IsNullOrEmpty(str) - if you'd like to check string value has been provided

    string.IsNullOrWhiteSpace(str) - basically this is already a sort of business logic implementation (i.e. why " " is bad, but something like "~~" is good).

    My advice - do not mix business logic with technical checks. So, for example, string.IsNullOrEmpty is the best to use at the beginning of methods to check their input parameters.

    0 讨论(0)
提交回复
热议问题