Conditionals are a common spot for the unintended creation of un-maintainable and un-readable code. To mitigate complicated conditionals, refactoring with Decompose Conditional always helps in conveying what you're trying to do. In other times, it's simply a matter of making the conditional logic itself less complicated. An oft-overlooked operator within C#, or within any language that supports it, is mutual exclusivity, or XOR. This is provided by the ^ character in C#. XOR states that a conditional will return true if one operand is true but not the other. The following demonstrates the differences between AND, OR and XOR.
AND
| Operand |
Operand |
Result |
| False |
False |
False |
| False |
True |
False |
| True |
False |
False |
| True |
True |
True |
OR
| Operand |
Operand |
Result |
| False |
False |
False |
| False |
True |
True |
| True |
False |
True |
| True |
True |
True |
XOR
| Operand |
Operand |
Result |
| False |
False |
False |
| False |
True |
True |
| True |
False |
True |
| True |
True |
False |
Note again that XOR returns false if both are true or both are false, but returns true when only one operand is true.
When used appropriately, XOR can greatly simplify a conditional statement and ease of readability. Consider the following conditional: ((a > 0 && b <= 0) || (b > 0 && a <= 0)). Using the XOR operator, this conditional can be simplified to: (a > 0 ^ b > 0). Clean, simple, and easy to read. A review of other C# operators on the MSDN site may lead to the discovery of other coding simplifications that you were not aware of or had long forgotten...or more concisely: (not aware of ^ long forgotten). Sorry, had to do it.
Billy McCafferty
Posted
11-24-2007 8:47 AM
by
Billy McCafferty