Friday, March 4, 2011

KnowDotNet: String.IsNullOrEmpty

Do you ever find yourself in a situation where you need to know whether a string is Null or empty. The following gist shows some code that tests this.

(if you can't see the gist please click here)



The output of this code is as follows:

Is Null: True
Is Null: False
Is Null: False
Is Empty: False
Is Empty: True
Is Empty: True
IsNullOrEmpty: True
IsNullOrEmpty: True
IsNullOrEmpty: True

You will see that test1 is null and therefore not considered empty test2 and test3 have String.Empty or "" assigned and are both considered empty, but not null. In some scenario's you may not know necessarily what result from a function or somewhere else and you have to test for null AND equality to an empty string (or a string of Length == 0) Note: String.Empty is equal to ""

This function conveniently does both tests for you

No comments:

Post a Comment