#1,106 – Using the Logical Exclusive OR Operator

You can use the exclusive OR (^) operator to do a bitwise exclusive OR operation.  The operands in this case are integer-based types.

You can also use the exclusive OR operator on boolean operands.  The result of the operation is true if exactly one of the operands (but not both) is true.

  • false ^ false => false
  • false ^ true => true
  • true ^ false => true
  • true ^ true => false
            bool itsThursday = DateTime.Now.DayOfWeek == DayOfWeek.Thursday;
            bool itsMay = DateTime.Now.Month == 5;

            // Wear red shirt in May, wear red shirt every Thursday,
            // but don't wear red shirt on Thursdays in May
            bool wearRedShirt = itsThursday ^ itsMay;

            Console.WriteLine("Thursday:{0}, May:{1}, RedShirt:{2}", itsThursday, itsMay, wearRedShirt);

1106-001

Advertisement