According to the C# Language Specification:
The
true
andfalse
unary operators require pair-wise declaration. A compile-time error occurs if a class declares one of these operators without also declaring the other.
This seems like a strange choice, since these two opeators, despite having names that seem related, have distinct uses.
Complete list of uses for operator true
:
- It allows the type to be used instead of a
bool
in anif
,while
,do
, orfor
statement, and as a first operand to the ternary? :
operator. (Relevant only if the type does not also have a matching implicit conversionimplicit operator bool
.) - If the same struct/class overloads the
operator |
in an appropriate way, it allows the use of short-circuiting operator||
as well.
Complete list of uses for operator false
:
- If the same struct/class overloads the
operator &
in an appropriate way, it allows the use of short-circuiting operator&&
as well.
Note that operator false
is only meaningful if operator &
is overloaded by the same type. Never is operator false
relevant for if
, while
etc. If you want to "negate" instances of your type, overload unary operator !
("not") instead.
So there seem to be legitimate uses where you need operator true
but not operator false
, or vice versa.
For example if I need only use (1) above, I overload operator true
(and possibly operator !
as well). But I might not want to overload &
, so it is meaningless to have to write the operator false
.
And in the opposite direction, I may design a type where I can &
instances together, and there may be a use of a short-circuit &&
as well, use (•), so I would overload operator false
. But that does not necessarily mean I want my type to have |
and ||
, much less that I require my type to be usable inside an if
, while
, etc.
There is no requirement to overload |
and &
"pairwise".
Instead of the actual restriction, it would be much more useful to specify:
(hypothetical) A compile-time error occurs if a class or struct overloads
operator false
without a matching overload foroperator &
.
The way things are, people are forced (by the C# spec) to write operator false
members that have absolutely no chance of ever being invoked.
The question: What is the motivation or historical reason for requiring operator true
and operator false
to go together?