6.5 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.
|