The most appropriate way to check for empty strings in C #

What is the best way to check for empty strings (I'm not a question of initialization! ) 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. :)

+42
string comparison c #
Oct 24 '11 at 7:52
source share
7 answers

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

Instead, compare using String.Length == 0

The difference between String.Empty and "" very small. String.Empty will not create any object, and "" will create a new object in memory for verification. Therefore, string.empty is better at managing memory. But comparing with String.Length == 0 would be even faster and the best way to check for an empty string.

+66
Oct 24 '11 at 8:27
source share

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

+26
Oct 24 '11 at 7:55
source share
 string.IsNullOrEmpty(a) 

it will check as NULL || EMPTY

this is the implementation:

 public static bool IsNullOrEmpty(string value) { if (value != null) { return (value.Length == 0); } return true; } 
+13
Oct 24 2018-11-11T00: 00Z
source share

You can also use Length

 string input = ""; if (input != null) { if (input.Length == 0) { } } 
+2
Oct 24 '11 at 7:55
source share

Create an extension method for a full check:

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

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

+1
Oct 24 2018-11-11T00:
source share

The value of String.Empty will be decrypted only at runtime, but on the other hand, the value of "" is known at compile time.

This is the only difference between the two.

But coming to best practice, if tomorrow M $ decides that due to some reason an empty value should be used as an “instead”, then your code should be changed every time. Therefore, in this case, it is best to use String.Empty.

This is the same practice as for Path.Combine.

0
Oct 24 '11 at 8:09
source share

Late Arrival:

 if a == "" 

will cause CA1820 warning about code analysis, so you should definitely not do this. For a complete analysis, see CA1820: checking empty strings using string length

0
Sep 06 '17 at 14:27
source share



All Articles