Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition for a non-empty string

Tags:

c#

I've been debating what seems like a small, trivial idea, but I am curious if there is more to it. Is there a difference between using the following two conditions to detect if a string is not empty? Are there any cases where this would return different results, or any subtleties that makes one a better choice?

str != ""

or

str.Length > 0
like image 905
Scott P Avatar asked Dec 14 '25 00:12

Scott P


1 Answers

If str is null, then str != "" will return true, but str.Length > 0 will throw a NullReferenceException. Other than that, they are equivalent.

But there are also a few other methods might use, like string.IsNullOrEmpty or string.IsNullOrWhiteSpace.

like image 181
p.s.w.g Avatar answered Dec 15 '25 13:12

p.s.w.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!