Although we’ve just warned you away from wildly implementing overloaded arithmetic operators, the comparison operators, especially `==`

, are another story. It’s very common to overload the `==`

operator to determine whether two objects are equal. What “equal” means is up to you, although your criteria should be reasonable. You might decide that two `Employee`

objects are equal if they have the same name, or you may decide that simply having the same employee ID is sufficient.

Overloading the `==`

operator works the same as overloading any other operator. Simply use the keyword `operator`

with the `==`

symbol, and place your code inside the method. The `==`

operator always returns a Boolean (true or false), so you’ll need to declare the operator as a `public static bool`

. For example, for the `Fraction`

class, your operator might look like this:

public static bool operator== ( Fraction lhs, Fraction rhs ) { if ( lhs.denominator == rhs.denominator && lhs.numerator == rhs.numerator ) { return true; } // code here to handle unlike fractions return false; }

Notice that there’s no `else`

clause here. If the numerator and denominator are equal, the operator returns `true`

, and exits. If they’re not equal, the `return`

statement after the `if`

is executed, so there’s no need for an `else`

.

C# insists that if you overload the equals operator, you must also overload the not-equals operator (`!=`

). It’s good programming practice to have the inequality operator delegate its work to the equality operator, ...

Start Free Trial

No credit card required