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?
What about this:
return (a == null) != (b == null);
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)).
You could use the xor operator
bool CheckForNull(object a, object b)
{
return (a == null ^ b == null);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With