Conditional XOR?

86,081

Solution 1

In C#, conditional operators only execute their secondary operand if necessary.

Since an XOR must by definition test both values, a conditional version would be silly.

Examples:

  • Logical AND: & - tests both sides every time.

  • Logical OR: | - test both sides every time.

  • Conditional AND: && - only tests the 2nd side if the 1st side is true.

  • Conditional OR: || - only test the 2nd side if the 1st side is false.

Solution 2

Question is a bit outdated but...

It's how this operator should work:

true xor false = true
true xor true = false
false xor true = true
false xor false = false

This is how != operator works with bool types:

(true != false) // true
(true != true) // false
(false != true) // true
(false != false) // false

So as you see unexisting ^^ can be replaced with existing !=

Solution 3

There is the logical XOR operator: ^

Documentation: C# Operators and ^ Operator

Solution 4

Just as a clarification, the ^ operator works with both integral types and bool.

See MSDN's ^ Operator (C# Reference):

Binary ^ operators are predefined for the integral types and bool. For integral types, ^ computes the bitwise exclusive-OR of its operands. For bool operands, ^ computes the logical exclusive-or of its operands; that is, the result is true if and only if exactly one of its operands is true.

Maybe the documentation has changed since 2011 when this question was asked.

Solution 5

As asked by Mark L, Here is the correct version:

 Func<bool, bool, bool> XOR = (X,Y) => ((!X) && Y) || (X && (!Y));

Here is the truth table:

 X | Y | Result
 ==============
 0 | 0 | 0
 1 | 0 | 1
 0 | 1 | 1
 1 | 1 | 0

Reference: Exclusive OR

Share:
86,081
Gilad Naaman
Author by

Gilad Naaman

Updated on May 04, 2020

Comments

  • Gilad Naaman
    Gilad Naaman almost 4 years

    How come C# doesn't have a conditional XOR operator?

    Example:

    true  xor false = true
    true  xor true  = false
    false xor false = false