How do you overload the true/false operators to make a custom type usable directly in an 'if' statement or as a boolean condition?
Short answer
Overloading 'true' and 'false' as static operators lets instances of your type be evaluated directly in boolean contexts (if, while, &&, ||) even though your type ISN'T actually 'bool' — the compiler calls your 'true' operator implementation wherever it needs to test the…
Advertisement
AModel answer
Overloading 'true' and 'false' as static operators lets instances of your type be evaluated directly in boolean contexts (if, while, &&, ||) even though your type ISN'T actually 'bool' — the compiler calls your 'true' operator implementation wherever it needs to test the truthiness of your custom type.
public struct OptionalValue {
public bool HasValue;
public static bool operator true(OptionalValue v) => v.HasValue;
public static bool operator false(OptionalValue v) => !v.HasValue;
}
OptionalValue opt = new OptionalValue { HasValue = true };
if (opt) { Console.WriteLine("Has a value!"); } // works, thanks to the true/false operatorsReal-world example
Building a custom nullable-like or Result-like value type that can be tested directly in conditional expressions without an explicit .HasValue check.
Likely follow-ups
- Why must you overload BOTH true and false together, and never just one alone?
Related topics