9

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?

Community
  • 1
  • 1
Matt
  • 25,943
  • 66
  • 198
  • 303
  • 8
    Is there a functional reason you're not doing String.IsNullOrEmpty(mystring)? – JustLoren Sep 29 '09 at 18:02
  • http://stackoverflow.com/questions/151472/what-is-the-difference-between-string-empty-and , http://stackoverflow.com/questions/810442/whats-the-most-efficient-way-to-determine-whether-an-untrimmed-string-is-empty-i – womp Sep 29 '09 at 18:05
  • I didn't know about it until just now! :-) Woot stackoverflow.... – Matt Sep 29 '09 at 18:06
  • Exact duplicate of http://stackoverflow.com/questions/10230/checking-for-string-contents-string-length-vs-empty-string – Drew Noakes Sep 29 '09 at 19:03

4 Answers4

42

I prefer

String.IsNullOrEmpty(myString)

Just in case it contains a null value.

Matthew Groves
  • 25,181
  • 9
  • 71
  • 121
AdamW
  • 1,061
  • 10
  • 14
  • 2
    String.IsNullOrEmpty(mystring) – Syed Tayyab Ali Sep 29 '09 at 18:10
  • I prefer `string.IsNullOrEmpty` because `string` is always a correct alias for `System.String` and is therefor consistent with the other "common types". (Although having a different `String` in scope would just be silly.) –  Apr 06 '12 at 05:36
9

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.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
4

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

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
2

As long as your string isn't a null reference then it doesn't really matter, however in the event that it is, neither will work and you may want to consider string.IsNullOrEmpty(mystring);

Quintin Robinson
  • 81,193
  • 14
  • 123
  • 132