Equals and value types

C

cronusf

In my book they give a sample Complex class implementation and it
implements:

override bool Equals(object rhs)
{...}

public book Equals(Complex rhs) // IEquatable<Complex>
{...}

public static bool operator==(Complex lhs, Complex rhs)
{...}

My question is, what is the point of implementing Equals when
operator== is defined?

Also, when would the "object" version of Equals ever be called instead
of the specific type version? Obviously it would be called if you
passed an object, but I can't see why that would ever happen in
practice.
 
J

Jon Skeet [C# MVP]

In my book they give a sample Complex class implementation and it
implements:

override bool Equals(object rhs)
{...}

public book Equals(Complex rhs) // IEquatable<Complex>
{...}

public static bool operator==(Complex lhs, Complex rhs)
{...}

My question is, what is the point of implementing Equals when
operator== is defined?

Because otherwise hash tables won't work properly - or anything else
which calls Equals.

Also bear in mind that Equals is applied polymorphically whereas ==
isn't.
Also, when would the "object" version of Equals ever be called instead
of the specific type version? Obviously it would be called if you
passed an object, but I can't see why that would ever happen in
practice.

It *often* happens in practice - any time a piece of code compares two
objects without knowing their types at compile-time. Finding an entry
in a list, or looking up a key in a hashtable are the most obvious
examples.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top