Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In .NET, which is best, mystring.Length == 0 or mystring == string.Empty? [duplicate]

Possible Duplicate:
Checking for string contents? string Length Vs Empty String

In .NET, which is best,

if (mystring.Length == 0)

or

if (mystring == string.Empty)

It seems that these would have the same effect, but which would be best behind the scenes?

like image 519
Matt Avatar asked Sep 29 '09 18:09

Matt


3 Answers

I prefer

String.IsNullOrEmpty(myString)

Just in case it contains a null value.

like image 92
AdamW Avatar answered Oct 13 '22 00:10

AdamW


Use the one that makes the most sense to you, logically. The difference in performance is meaningless, so the "best" option is the one that you'll understand next year when you look back at this code.

My personal preference is to use:

if(string.IsNullOrEmpty(mystring))

I prefer this since it checks against null, too, which is a common issue.

like image 39
Reed Copsey Avatar answered Oct 12 '22 23:10

Reed Copsey


The difference is so small I would consider it insignificant (the length property on a string is not calculated - it is a fixed value).

like image 40
Andrew Hare Avatar answered Oct 12 '22 23:10

Andrew Hare