Revisit Object.Equals

  • Thread starter Thread starter nick_nw
  • Start date Start date
N

nick_nw

Hi All,

Just been re-reading Applied MS .Net Framework Programming (been about
2 years since I last read it) and came across the chapter on Equals,
==, and GetHashCode. It dawned on me that after 2 years of c# .net
programming I have never overridden any of these methods.

But why would I? For example, I have a simple class:

class MC
{
int i;

MC (int i)
{
this.i = i;
}
}

If I then implemented:

MC c1, c2;
c1 = new MC (2);
c2 = new MC (2);

bool theSame = (c1 == c2); // Would this return false because
different instances?
bool theSame2 = (c1.Equals (c2)); // Is this the same as the above?
 
Hello nick_nw,

It depends on what you are trying to compare - equality or reference identity.
Jon gave good explanation http://www.yoda.arachsys.com/csharp/faq/#equals

For value types you need to override Equals to gain performance, because
standard realization uses reflection for this

n> Hi All,
n>
n> Just been re-reading Applied MS .Net Framework Programming (been
n> about 2 years since I last read it) and came across the chapter on
n> Equals, ==, and GetHashCode. It dawned on me that after 2 years of
n> c# .net programming I have never overridden any of these methods.
n>
n> But why would I? For example, I have a simple class:
n>
n> class MC
n> {
n> int i;
n> MC (int i)
n> {
n> this.i = i;
n> }
n> }
n> If I then implemented:
n>
n> MC c1, c2;
n> c1 = new MC (2);
n> c2 = new MC (2);
n> bool theSame = (c1 == c2); // Would this return false because
n> different instances?
n> bool theSame2 = (c1.Equals (c2)); // Is this the same as the
n> above?
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsch
 
Why would you override equals/==?
For example, if you wanted to use instances of particular classes as keys in
a hashtable. Or if you wanted to have a list of instances and wanted to know
if you have equal instances inside.
Basically, if you wanted to provide equality semantics for reference types
based on field values instead of object identities.
 
I'm at home, and I don't have C#/VS here. I'l; try it on Monday at
work, hence ng question.
 

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

Back
Top