String equality with null handling

Brady Moritz picture Brady Moritz · Mar 3, 2013 · Viewed 48.8k times · Source

I will often use this code to compare a string:

if(!string.IsNullOrEmpty(str1) && str1.Equals(str2)){
    //they are equal, do my thing
}

This handles the null case first etc.

Is there a cleaner way to do string comparison, perhaps with a single method call that will handle possible null values? I simply want to know that the strings are not equal if the testing value is null.

(I'm having dejavu that I may have asked this before, I apologize if so)


Update: In my case, the str2 is a known good string to compare to, so I don't need to check it for null. str1 is the "unknown" string which may be null, so I want to say "str1 does not equal str2" in the cases where str1 is null...

Answer

SLaks picture SLaks · Mar 3, 2013

Unlike Java, C# strings override the == operator:

if (str1 == str2)

If you want a case-insensitive comparison:

if (String.Equals(str1, str2, StringComparison.OrdinalIgnoreCase)