Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional XOR?

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

Example:

true  xor false = true true  xor true  = false false xor false = false 
like image 925
Gilad Naaman Avatar asked Jun 28 '11 14:06

Gilad Naaman


2 Answers

Conditional xor should work like this:

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

But this is how the != operator actually works with bool types:

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

So as you see, the nonexistent ^^ can be replaced with existing !=.

like image 125
piotrpo Avatar answered Oct 14 '22 23:10

piotrpo


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.

like image 34
The Evil Greebo Avatar answered Oct 15 '22 00:10

The Evil Greebo