C#
Operator definitions, but not & or &&:
boolean a = true; boolean b = true; boolean a_and_b = a & b; if (a) System.Console.WriteLine("a is true"); if (b) System.Console.WriteLine("b is true"); if (a_and_b) System.Console.WriteLine("a and b is true"); else System.Console.WriteLine("a and b is false"); // ideally, put this away in an innocuous file public class boolean { private bool Value; public boolean(bool b) { Value = b; } public boolean(int i) { Value = i != 0; } public static implicit operator int(boolean b) => b.Value ? 0 : 1; public static implicit operator boolean(int i) => new boolean(i); public static implicit operator boolean(bool b) => new boolean(b); public static bool operator true(boolean b) => b.Value; public static bool operator false(boolean b) => b.Value; } Notes
- Uses the operator allowing a class to have a truth value to separately evaluate a and b truth values.
a & b= false is accomplished via code in implicit type casts.- Had to use
&and go throughintinstead of&&because unfortunately order of operations has implicit conversion toboolas higher priority to thetrue/falseoperators. - I've used
booleanto mimic the Java keyword (and probably others), but you could useBooleanand shadowSystem.Booleanto try to trick those more familiar with C#. - As a bonus, if a = false, b = false, then a & b = true, so two wrongs make a right.
- I recommend this as a bug finding exercise for Java programmers being introduced to C# (if you don't like them).
A variant
Using similar implicit conversions, we can use the native && operator, but I like this solution less as I've not found a way to not declare the initial variables false (or use negation), resulting in immediately suspicious looking code:
boolean a = false; boolean b = false; boolean a_and_b = a && b; if (a) System.Console.WriteLine("a is true"); if (b) System.Console.WriteLine("b is true"); if (a_and_b) System.Console.WriteLine("a and b is true"); else System.Console.WriteLine("a and b is false"); public struct boolean { private bool Value; public static implicit operator boolean(bool b) => new boolean { Value = b }; public static implicit operator bool(boolean b) => !b.Value; }