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

后端 未结 9 716
广开言路
广开言路 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;
        }
    
        /// 
        /// Indicates whether a specified string is null, empty, or consists only of white-space characters.
        /// 
        /// 
        /// 
        /// true if the  parameter is null or , or if  consists exclusively of white-space characters.
        /// 
        /// The string to test.
        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;
        }
    

提交回复
热议问题