Most advisable way of checking empty strings in C#

ぐ巨炮叔叔 提交于 2020-01-09 12:41:48

问题


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

string a;

// some code here.......


if(a == string.Empty)

or

if(string.IsNullOrEmpty(a))

or

if(a == "")

any help would be appreciated. :)


回答1:


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.




回答2:


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




回答3:


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



回答4:


Create an extension method for complete check:

public static bool IsEmpty(this string s)
{
  if(s == null) return true;
  return string.IsNullOrEmpty(s.Trim()); // originally only (s)
}

Sorry, not good code, fixed. Now this will tell you, if the string is empty or if is empty after trimming.




回答5:


You can use Length as well

string input = "";

if (input != null)
{
    if (input.Length == 0)
    {

    }
}  



回答6:


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




回答7:


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.



来源:https://stackoverflow.com/questions/7872633/most-advisable-way-of-checking-empty-strings-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!