Most advisable way of checking empty strings in C#

后端 未结 7 865
抹茶落季
抹茶落季 2020-12-13 01:51

What is the best way for checking empty strings (I\'m not asking about initializing!) in C# when considering code performance?(see code bel

相关标签:
7条回答
  • 2020-12-13 02:28

    Do not compare strings to String.Empty or "" to check for empty strings.

    Instead, compare by using String.Length == 0

    The difference between string.Empty and "" is very small. String.Empty will not create any object while "" will create a new object in the memory for the checking. Hence string.empty is better in memory management. But the comparison with string.Length == 0 will be even faster and the better way to check for the empty string.

    0 讨论(0)
  • 2020-12-13 02:29

    String.Empty value will be deciphered at run time only but on the other side "" value is known at the compile time itself.

    That's the only difference between those two.

    But coming to the best practice, if tomorrow M$ decides that the empty string value should be used as '' instead of "" due to some reason, then your code has to be changed every where. So in that case its best to use String.Empty.

    Its the same practice used with Path.Combine as well.

    0 讨论(0)
  • 2020-12-13 02:32

    You can use Length as well

    string input = "";
    
    if (input != null)
    {
        if (input.Length == 0)
        {
    
        }
    }  
    
    0 讨论(0)
  • 2020-12-13 02:33

    I think the best way is if(string.IsNullOrEmpty(a)) because it's faster and safer than the other methods.

    0 讨论(0)
  • 2020-12-13 02:42

    A late arrival:

    if a == ""
    

    will give rise to Code Analysis warning CA1820, so you definitely shouldn't do that. For a full analysis see CA1820: Test for empty strings using string length

    0 讨论(0)
  • 2020-12-13 02:44
    string.IsNullOrEmpty(a)
    

    it will check both NULL || EMPTY

    this is the Implementation :

    public static bool IsNullOrEmpty(string value)
    {
        if (value != null)
        {
            return (value.Length == 0);
        }
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题