I'm making an if statement in C# that I would like to return true if ONLY one of the parameters is true. I'll use ||
in the example because that's the closest thing I can think of:
int a = 1;
int b = 2;
int c = 3;
if(a == 1 || b == 2)
{
Console.Log("The first statement is true")
}
if(a == 1 || b == 3)
{
Console.Log("The second statement is true")
}
if(a == 0 || b == 0 || c == 3)
{
Console.Log("The third statement is true")
}
if(a == 1 || b == 0 || c == 3)
{
Console.Log("The fourth statement is true")
}
//Output:
//The second statement is true
//The third statement is true
Again, think of the ||
as the operator I'm looking for. Does such an operator exist, or should I define my own boolean function?
For two expressions, you can just use XOR:
if (a == 1 ^ b == 0)
For more than two, you could do something like:
if (new[] { a == 1, b == 0, c == 2 }.Count(x => x) == 1)
That basically counts all the "true" elements of the array constructed from the expressions, and checks that the count is 1.
Admittedly that evaluate all the conditions first, and will count all of them even if the first two are true (so the final one is irrelevant). If that ends up being expensive for you, there are more complex alternatives, but I'd definitely stick to something like this unless it's actually a problem.
See more on this question at Stackoverflow