Skip to Main Content
Programming C#
book

Programming C#

by Jesse Liberty
July 2001
Intermediate to advanced content levelIntermediate to advanced
688 pages
16h 14m
English
O'Reilly Media, Inc.
Content preview from Programming C#

The Equals Operator

If you overload the equals operator (==), it is recommended that you also override the virtual Equals( ) method provided by object and route its functionality back to the equals operator. This allows your class to be polymorphic and provides compatibility with other .NET languages that do not overload operators (but do support method overloading). The FCL classes will not use the overloaded operators but will expect your classes to implement the underlying methods. Thus, for example, ArrayList expects you to implement Equals( ).

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

public override bool Equals(object o)

By overriding this method, you allow your Fraction class to act polymorphically with all other objects. Inside the body of Equals( ) you will need to ensure that you are comparing with another Fraction, and if so you can pass the implementation along to the equals operator definition that you’ve written.

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 will evaluate true if o is in fact a type compatible with Fraction.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming C#, Second Edition

Programming C#, Second Edition

Jesse Liberty
Programming C# 12

Programming C# 12

Ian Griffiths
Programming C# 8.0

Programming C# 8.0

Ian Griffiths

Publisher Resources

ISBN: 0596001177Supplemental ContentCatalog PageErrata