9

What is the best way to check if only A is null or only B is null? I have been trying many different ways to find something that feels clean, and this is how convoluted it has gotten:

bool CheckForNull(object a, object b)
{
    if(a == null && b == null)
    {
        return false;
    }
    if(a == null || b == null)
    {
        return true;
    }
    return false;
}

My best (and the most obvious) version is:

bool CheckForNull(object a, object b)
{
    return a == null && b != null || a != null && b == null;
}

But I don't really like that either. (Sure I could add parenthesis...)

Is there a standard way of doing this that I never learned?

0

3 Answers 3

21

What about this:

return (a == null) != (b == null);
2

If you need/want to use xor, you could use:

return (a == null) ^ (b == null);

but for that to work, true has to evaluate to the same 'value'.

But in this case, I think I would keep it as simple as possible. Your second version doesn't look so bad actually:

return a == null && b != null || a != null && b == null;

and there is a possibility of an early exit. (and if lucky, the compiler might even optimize this to be executed in parallel (instruction pipelining)).

3
  • 1
    True has to evaluate to the same value? Watcha mean? When is true not equal to true?
    – Evorlor
    Commented Feb 22, 2016 at 1:56
  • 1
    @Evorlor Depending on the language, anything that is not zero can evaluate to true (0 is false, all else is true). So if your left 'true' is 1 and the right one is 2, the xor won't work as expected.
    – Danny_ds
    Commented Feb 22, 2016 at 11:17
  • 2
    The question has the c# tag. No need wondering which language. Commented Mar 5, 2021 at 16:57
1

You could use the xor operator

bool CheckForNull(object a, object b)
{
    return (a == null ^ b == null);
}
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.