Logical Pairs

It is quite common to overload the equals operator (==) to test whether two objects are equal. C# insists that if you overload the equals operator, you must also overload the not-equals operator (!=). Similarly, the less than (<) and greater than (>) operators must be paired, as must the less than or equals (<=) and greater than or equals (>=) operators.

The Equals Operator

The Object class (which is the root of every class in C#) offers a virtual method called Equals(). (Virtual methods are discussed in Chapter 11.) If you overload the equals operator (==), it is recommended that you also override the Equals() method.

Overriding the Equals() method allows your class to be polymorphic and provides compatibility with other .NET languages that do not overload operators (but do support method overloading).

Tip

The classes in the .NET Framework Class Library do not use the overloaded operators but do expect your classes to implement the underlying methods, such as Equals().

The Object class implements the Equals() method with this signature:

public virtual bool Equals(object o)

From this signature you can see that your override of this method will take an object as a parameter and return a bool (true if the two objects are equal).

By overriding this method, you allow your Fraction class to act polymorphically with all other objects. That is, anywhere you can call Equals() on two Objects, you can call Equals() on two Fractions.

Inside the body of Equals(), you need to ...

Get Learning C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.