You cannot override an increment in an existing type, but you can easily write a wrapper. Example:
struct Bool : IEquatable<Bool> { bool value; public Bool(bool b) { value = b; } public static Bool operator ++ (Bool b) => Bool.True; public static Bool operator -- (Bool b) => Bool.False; public static bool operator true (Bool b) => b.value; public static bool operator false (Bool b) => !b.value; public static Bool operator | (Bool b1, Bool b2) => new Bool(b1.value || b2.value); public static Bool operator & (Bool b1, Bool b2) => new Bool(b1.value && b2.value); public static implicit operator Bool(bool v) => new Bool(v); public static readonly Bool True = new Bool(true); public static readonly Bool False = new Bool(false); public bool Equals(Bool other) => value == other.value; public static Bool operator == (Bool l, Bool r) => l.value == r.value; public static Bool operator != (Bool l, Bool r) => l.value != r.value; public override bool Equals(object obj) => (obj is Bool) && Equals((Bool)obj); public override int GetHashCode() => value.GetHashCode(); public override string ToString() => value.ToString(); }
Example of use:
class Program { static void Main(string[] args) { Bool x; x = false; Console.WriteLine(++x); x = Bool.False; Console.WriteLine(x++); Console.WriteLine(x); Bool b1 = Bool.False; if (++b1) Console.WriteLine("preincreement true"); else Console.WriteLine("preincreement false"); Bool b2 = Bool.False; if (b2++) Console.WriteLine("postincreement true"); else Console.WriteLine("postincreement false"); if (ComputeFalse() && ComputeTrue()) { /* do nothing */ } var b3 = (b1 == b2); if (b3++) { /* do nothing */ } } static Bool ComputeTrue() { Console.WriteLine("computing true"); return Bool.True; } static Bool ComputeFalse() { Console.WriteLine("computing false"); return false; } }
The output of the program:
True
False
True
preincreement true
postincreement false
computing false
bool, you can use the expressiona ^= true, which cyclically assigns the variableavalues true / false / true / false / ... - kmv