String Compare where null and empty are equal

Solution 1:

Doesn't eliminate the extra underlying comparisons, but for the sexiness factor, you could use something like this:

(strA ?? "") == (strB ?? "")

or the slightly less sexy, but preferable form:

(strA ?? string.Empty) == (strB ?? string.Empty)

Solution 2:

Since you've got hundreds of comparisons to do, it sounds like you want a single function to call so that you can reduce the clutter and repetition in your code. I don't think there is a built-in function to do a null/empty string/comparison check all in one, but you could just make one yourself:

static class Comparison
{
    public static bool AreEqual(string a, string b)
    {
        if (string.IsNullOrEmpty(a))
        {
            return string.IsNullOrEmpty(b);
        }
        else
        {
            return string.Equals(a, b);
        }
    }
}

Then you could just use a single call to your function for each comparison:

        if(Comparison.AreEqual(strA[0], strB[0])) { // ... }
        if(Comparison.AreEqual(strA[1], strB[1])) { // ... }
        if(Comparison.AreEqual(strA[2], strB[2])) { // ... }
        if(Comparison.AreEqual(strA[3], strB[3])) { // ... }

This approach is also easier to expand if you later find that you need to worry about additional situations, such as ignoring whitespace at the beginning or ending of strings; you can then just add more logic to your function to do some trimming or whatever and you won't have to make any modifications to the hundreds of lines of code calling your function.

Solution 3:

Not as sexy as ??, but you could avoid the double comparison part of the time if you short-circuit it:

string.IsNullOrEmpty( strA ) ? string.IsNullOrEmpty( strB ) : (strA == strB )

Solution 4:

What about

strA ?? "" == strB ?? ""