Consider null and empty strings as equivalent

1

I want to compare strings that come from two different sources. If they are different, I will do something. More or less like this:

if (foo != bar)
{
    noop();
}

However, in my specific case, I am considering that an empty string and a null string are the same thing. In some languages such as Javascript such a code would suffice, but that's not the way it works in the .NET world ...

string foo = null;
string bar = "";
foo == bar; // false;

I know I can solve my problem with some preconversion of type:

foo = (foo != null ? foo : "");
bar = (bar != null ? bar : "");

But this bothers me, because it seems excessive. Is there a more minimalist way of making a comparison that considers null or void the same thing?

    
asked by anonymous 12.06.2014 / 19:46

2 answers

2

If you are only interested in a binary result, whether they are the same or not, why not:

bool iguais = string.IsNullOrEmpty(primeiraString) && string.IsNullOrEmpty(segundaString);

In this way, if the strings are null, null / empty or empty, iguais will be true .

Edit:

An example in .NetFiddle .

    
12.06.2014 / 20:04
2

If it will be used in more than one place, this is an implementation based on a SOzon response .

static class Comparacao
{
    public static bool SaoIguais(string a, string b)
    {
        if (string.IsNullOrEmpty(a))
        {
            return string.IsNullOrEmpty(b);
        }
        return string.Equals(a, b);
    }
}
    
12.06.2014 / 20:23