BlackWaspTM
C# Programming
.NET 1.1+

C# Logical Operator Overloading (2)

The tenth article in the C# Object-Oriented Programming tutorial continues the discussion of operator overloading. In this article, the overloading of the logical operators is described including how to enable the short-circuit Boolean logical operators.

Creating the Boolean OR (|) and XOR (^) Operators

Using similar code, we can add the Boolean OR and XOR operators to the Vector class. Add the following two operator overloads to the class to implement the two logical functions.

public static bool operator |(Vector v1, Vector v2)
{
    bool v1flag = !((v1.X == 0) && (v1.Y == 0));
    bool v2flag = !((v2.X == 0) && (v2.Y == 0));

    return v1flag | v2flag;
}

public static bool operator ^(Vector v1, Vector v2)
{
    bool v1flag = !((v1.X == 0) && (v1.Y == 0));
    bool v2flag = !((v2.X == 0) && (v2.Y == 0));

    return v1flag ^ v2flag;
}

Again, these operators can be tested using a modified Main method:

static void Main(string[] args)
{
    Vector v1 = new Vector(0, 0);
    Vector v2 = new Vector(10, 0);

    Console.WriteLine(v1 | v1);                 // Outputs "False"
    Console.WriteLine(v1 | v2);                 // Outputs "True"
    Console.WriteLine(v2 | v1);                 // Outputs "True"
    Console.WriteLine(v2 | v2);                 // Outputs "True"

    Console.WriteLine(v1 ^ v1);                 // Outputs "False"
    Console.WriteLine(v1 ^ v2);                 // Outputs "True"
    Console.WriteLine(v2 ^ v1);                 // Outputs "True"
    Console.WriteLine(v2 ^ v2);                 // Outputs "False"
}

Overloading the Unary Boolean Logical Operator

Only one unary Boolean logical operator exists. This is the NOT operator (!) that switches a Boolean value between true and false. When overloaded using the unary syntax below, the value returned should be the opposite of the Boolean representation of the object. As with other unary operators, the type of the operand provided must be the same as the class that the declaration appears within.

public static bool operator !(op-type operand)

Creating the Boolean NOT Operator (!)

The NOT operator for the Vector class will examine the contents of the X and Y properties. As described above, if both co-ordinates are zero, the Boolean value for the object is false. However, as this is the NOT operator, we will perform the check and return true only when both values are zero. Add the following code to the class to provide the NOT operator:

public static bool operator !(Vector v)
{
    return ((v.X == 0) && (v.Y == 0));
}

To test that the operator is working correctly, modify the Main method as follows:

static void Main(string[] args)
{
    Vector v1 = new Vector(0, 0);
    Vector v2 = new Vector(10, 0);

    Console.WriteLine(!v1);                     // Outputs "True"
    Console.WriteLine(!v2);                     // Outputs "False"
}
26 November 2007