Overloading the true and false operators

If you need to overload the true or false operators in your class or structure, define a method with the following characteristics:

• The keyword operator

• The operator being overloaded

• A parameter list specifying a single parameter of the type of class or structure containing the overloaded operator method

For an example, look at Listing 10-6. It modifies the point class to evaluate to true whether the point is on the origin and to evaluate to false otherwise.

Listing 10-6: Overloading the True and False Operators class Point {

public int X; public int Y;

public static bool operator true (Point RValue) {

return true; return false;

public static bool operator false (Point RValue) {

return false; return true;

public static void Main() {

Point MyPoint = new Point();

if(MyPoint)

System.Console.WriteLine("The point is at the origin.");

else

System.Console.WriteLine("The point is not at the origin.");

Overloading the true and false operators allows objects of the Point class to be used as Boolean expressions, as in the if statement. Because the MyPoint object is not at the origin, the object evaluates to false, as shown in Figure 10-6.

^EfflrarjGŒBBBB

= M^UBttr I Hl^r,(i ! 11,„ 111 m, ¡i.^p, Iv^ >L i M Ln-J I U <, <t hr pnlnL la nul 1 Ik url*lJi-

iMlithril

Figure 10-6: Overloading the true and false operators

If either the true or false operators are overloaded for a class or structure, they both must be overloaded. If you overload one but not the other, the C# compiler issues an error message like the following:

error CS0216: The operator 'Point.operator true(Point)' requires a matching operator 'false' to also be defined

0 0

Post a comment