简体   繁体   中英

.NET string.IsNullOrWhiteSpace implementation

Folks, I was looking at the implementation of string.IsNullOrWhiteSpace in:

http://typedescriptor.net/browse/types/9331-System.String

Here is the implementation:

public static bool IsNullOrWhiteSpace(string value)
{
    if (value == null)
    {
        return true;
    }
    for (int i = 0; i < value.Length; i++)
    {
        if (char.IsWhiteSpace(value[i]))
        {
        }
        else
        {
            goto Block_2;
        }
    }
    goto Block_3;
    Block_2:
    return false;
    Block_3:
    return true;
}

Question: Isn't this over complicated? Can't the following implementation do the same job and be easier on the eye:

bool IsNullOrWhiteSpace(string value)
{
    if(value == null)
    {
        return true;
    }   
    for(int i = 0; i < value.Length;i++)
    {
        if(!char.IsWhiteSpace(value[i]))
        {
            return false;
        }
    }
    return true;
}

Is this implementation incorrect? Does it have a performance penalty?

The original code (from the reference source) is

public static bool IsNullOrWhiteSpace(String value) {
    if (value == null) return true; 

    for(int i = 0; i < value.Length; i++) { 
        if(!Char.IsWhiteSpace(value[i])) return false; 
    }

    return true;
}

You're seeing the output of a poor decompiler.

You are looking at C# that was recreated from the disassembled IL. I am sure that the actual implementation is closer to your example and does not use labels.

It must be typedescriptor's disassembler doing that.

When I look at the same function with JetBrain's dotPeek it looks like this:

 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;
    }

Shown below is an extension method I needed for older versions. I am not sure where I obtained the code from:

public static class StringExtensions
    {
        // This is only need for versions before 4.0
        public static bool IsNullOrWhiteSpace(this string value)
        {
            if (value == null) return true;
            return string.IsNullOrEmpty(value.Trim());
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM