Section 6.5. The Equality Operator


6.5. The Equality Operator

If you overload the equality 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 don't 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. The object class implements the Equals() method with this signature:

public virtual 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.

The compiler will also expect you to override GetHashCode, as explained next.




Programming C#(c) Building. NET Applications with C#
Programming C#: Building .NET Applications with C#
ISBN: 0596006993
EAN: 2147483647
Year: 2003
Pages: 180
Authors: Jesse Liberty

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net