O'Reilly logo

Learning C# 2005, 2nd Edition by Brian MacDonald, Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 compatible with other .NET languages that do not overload operators (but do support method overloading).

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, where “equality” is defined by the creator of the class).

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

Inside the body of Equals( ), you need to ensure that you are comparing one Fraction object with another Fraction object. If the other object is not a fraction, they cannot be equal, and you’ll return false.

    public override bool Equals(object o)
    {if ( ! (o is Fraction) )
         {
            return false;
         }
         return this == (Fraction) o;
    }

The is operator is used to check whether the runtime type of an object is compatible with the operand (in this case, Fraction). Thus o is Fraction evaluates true if o is, in fact, a Fraction or a type derived from ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required