
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Indirectly Overloading the &&, ||, and ?: Operators
|
121
This technique gives you complete control over the operations of the &&, ||, and ?:
operators.
Alternatively, you can simply add an implicit conversion to
bool:
public class ObjState
{
public ObjState(int state)
{
this.state = state;
}
public int state = 0;
public static implicit operator bool(ObjState obj)
{
if (obj.state == 0)
{
throw new InvalidOperationException( );
}
return (obj.state > 0);
}
}
This technique implements strict Boolean logic; the first technique (overriding the
&&, ||, and ?: operators) gives you more freedom to stray from implementing strict
Boolean logic.
Discussion
While you cannot overload the &&, ||, and ?: operators directly, you can overload them
indirectly by overloading the
&, |, true, and false operators. The &&, ||, and ?: opera-
tors then use the overloaded
&, |, true, and false operators for their calculations.
The
&& operator indirectly uses the false and & operators to perform a short-circuiting
AND operation. Initially, the
false operator is invoked to determine whether the
first object is equal to
false. If so, the righthand side of the expression is not evalu-
ated and
false is returned. If the false operator returns a true, the & operator is
invoked next to perform the ANDing operation on the two