I had always just used “if ( != null)” to check if a string exists and it seems to work fine, but I came across a forum post that said to use string.IsNullOrEmpty(Name) in response to someone who said that checking if a string is equal to null doesn’t work. This was news to me. Anyone know what’s going on with this? As far as I can tell, both methods work fine, although I found that using “if ( )” doesn’t work (even though it works fine for other objects) since it returns a “Cannot implicitly convert type string to bool” error.
I wish I could just use memory, as in assembly language, so I know what’s going on “under the hood”.
string s1 = "";
string s2 = null;
if (s1 == null) // false
if (strings.IsNullOrEmpty(s1)) // true
if (s2 == null) // true
if (strings.IsNullOrEmpty(s2)) // true
So string.IsNullOrEmpty(s1) is a shorthand for
s1 == null || s1 == ""
The comparison to null tells you if the reference in the variable is valid or not (string is a reference type).
The isNullOrEmpty says if the reference is valid AND if there is something in the variable (other than the empty string)
There is a IsNullOrWhiteSpacemethod when it’s telling you if there is any character in the variable which is not space, tab, enter or other white space.