Consider null and empty strings as equivalent to each other

Asked

Viewed 67 times

1

I want to compare strings that come from two different sources. If they’re different, I’ll do something. Something 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 certain languages such as Javascript a code like this would be enough, but that’s not how it works in the world . NET...

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

I know I can solve my problem with some pre-conversion type:

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

But it bothers me, because it seems excessive. Is there any more minimalist way to make a comparison that considers null or empty as the same thing?

2 answers

2


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

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

Thus, if strings are null, null/empty or empty, iguais will stay to true.

Edit:

An example in .Netfiddle.

  • 1

    Good. This is close enough to what I want. I will create a method that does this check, and in case of false, compare the strings to each other.

2

If you’re using it in more than one place, this is an implementation based on a reply from Sozão.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.