471,337 Members | 1,444 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,337 software developers and data experts.

Equals and value types

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.
Jul 5 '08 #1
1 1091
<cr*****@gmail.comwrote:
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.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon_skeet
C# in Depth: http://csharpindepth.com
Jul 5 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Bijay Kumar | last post: by
17 posts views Thread by Zeng | last post: by
4 posts views Thread by Kurt | last post: by
4 posts views Thread by Chris | last post: by
8 posts views Thread by Kenneth Baltrinic | last post: by
28 posts views Thread by Tony Johansson | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.