Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most advisable way of checking empty strings in C# [closed]

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. :)

like image 393
Allan Chua Avatar asked Oct 24 '11 07:10

Allan Chua


People also ask

How do you test if a string is empty in C?

To check if a given string is empty or not, we can use the strlen() function in C. The strlen() function takes the string as an argument and returns the total number of characters in a given string, so if that function returns 0 then the given string is empty else it is not empty.

Which function is used to check an empty string?

Answer: Use the === Operator You can use the strict equality operator ( === ) to check whether a string is empty or not.

How do I see empty strings?

Use the length property to check if a string is empty, e.g. if (str. length === 0) {} . If the string's length is equal to 0 , then it's empty, otherwise it isn't empty. Copied!

How do I check if a string is empty or NULL?

Using the isEmpty() Method The isEmpty() method returns true or false depending on whether or not our string contains any text. It's easily chainable with a string == null check, and can even differentiate between blank and empty strings: String string = "Hello there"; if (string == null || string.


2 Answers

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.

like image 139
Yogesh Avatar answered Sep 19 '22 08:09

Yogesh


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

like image 23
Gregory Nozik Avatar answered Sep 21 '22 08:09

Gregory Nozik