Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I best check if A xor B are null?

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?

like image 815
Evorlor Avatar asked Jan 06 '16 22:01

Evorlor


3 Answers

What about this:

return (a == null) != (b == null);
like image 174
Yacoub Massad Avatar answered Oct 15 '22 17:10

Yacoub Massad


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)).

like image 30
Danny_ds Avatar answered Oct 15 '22 18:10

Danny_ds


You could use the xor operator

bool CheckForNull(object a, object b)
{
    return (a == null ^ b == null);
}
like image 1
Scott Chamberlain Avatar answered Oct 15 '22 17:10

Scott Chamberlain