473,287 Members | 1,947 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

override GetHashCode

Hi All,
I don't understand very well this part of MSDN:
"Derived classes that override GetHashCode must also override Equals to
guarantee that two objects considered equal have the same hash code;
otherwise, Hashtable might not work correctly."
Does any one know, why we must also override Equals,
Please give my an example:)

Thanks,
Stoyan
Nov 16 '05 #1
5 9546
Hi Stoyan,

The Hashtable type requires that if two objects are equal, they must have
the same hash code value : when a key/value pair is added to a Hashtable,
the Hashtable uses the hash code of the key to determine the bucket that
stores the key. The bucket is then searched for a key which Equals the
given key (there might be more than one key in the bucket). If you wonder
why Equals is needed to find the key in the bucket : hashes can collide
(i.e. two different objects might generate the same hash - a hash
collision).
http://samples.gotdotnet.com/quickst...hashtable.aspx

Regards,
Bart

--
http://www.xenopz.com
"Stoyan" <St****@discussions.microsoft.com> wrote in message
news:FF**********************************@microsof t.com...
Hi All,
I don't understand very well this part of MSDN:
"Derived classes that override GetHashCode must also override Equals to
guarantee that two objects considered equal have the same hash code;
otherwise, Hashtable might not work correctly."
Does any one know, why we must also override Equals,
Please give my an example:)

Thanks,
Stoyan

Nov 16 '05 #2
Hi Bart,
I understand very well, if I override Equals, I must override and
GetHashCode() method.
but I don't understand for example:
I have two classes:
public class SomeType
{
public override int GetHashCode()
{ return 1;}
}
public class AnotherType
{
public override int GetHashCode()
{ return 1;}
}

SomeType a = new SomeType();
AnotherType b = new AnotherType();
Hashtable tbl = new Hashtable();
tbl.Add(a,a);
tbl.Add(b,b);
object a = tbl[a]; // this object is correct (SomeType)
object b = tbl[b]; // this object is correct (AnotherType)

In my case, why must also override Equals()?
I know, if hashcodes are different, Hashtable working better(faster)

Regards,
Stoyan

"Bart De Boeck" wrote:
Hi Stoyan,

The Hashtable type requires that if two objects are equal, they must have
the same hash code value : when a key/value pair is added to a Hashtable,
the Hashtable uses the hash code of the key to determine the bucket that
stores the key. The bucket is then searched for a key which Equals the
given key (there might be more than one key in the bucket). If you wonder
why Equals is needed to find the key in the bucket : hashes can collide
(i.e. two different objects might generate the same hash - a hash
collision).
http://samples.gotdotnet.com/quickst...hashtable.aspx

Regards,
Bart

--
http://www.xenopz.com
"Stoyan" <St****@discussions.microsoft.com> wrote in message
news:FF**********************************@microsof t.com...
Hi All,
I don't understand very well this part of MSDN:
"Derived classes that override GetHashCode must also override Equals to
guarantee that two objects considered equal have the same hash code;
otherwise, Hashtable might not work correctly."
Does any one know, why we must also override Equals,
Please give my an example:)

Thanks,
Stoyan


Nov 16 '05 #3
Stoyan wrote:
Hi All,
I don't understand very well this part of MSDN:
"Derived classes that override GetHashCode must also override Equals to
guarantee that two objects considered equal have the same hash code;
otherwise, Hashtable might not work correctly."
For hashtables to operate, the following must be true:

Equals(x,y) -> x.GetHashCode() == y.GetHashCode()
x.GetHashCode() != y.GetHashCode() -> !Equals(x,y)

This effectivly joins the partitioning that Equals imposes on objects
into larger sets, which rather neatly are numbered..., ready to put in
an index'ed array. Cunning thing, hashing :)

The above makes a constraint on how you can re-define GetHashCode
without redefining Equals.

Stricly speaking, if you use (keep the default) reference-equality the
only constraint on GetHashCode is that it is consistent:

x == y -> x.GetHashCode(x) == y.GetHashCode(y).
Does any one know, why we must also override Equals,
Well, strictly speaking... it's not required, but...
Please give my an example:)


In short, Hashtables usually does linear comparison, using Equals, of
the lookup key with every entry with the same hash-value modulo the size
of the hashtable. This also shows why choosing a hash-function with good
distribution is very important.

For hashing to be *usefull*, one usually calculates the hashcode on the
basis of the *value* of an object, not the reference, and *that's* why
you need to override Equals.

A minimalistic example:

class Foo {
public readonly int X;
public Foo(int x) { this.X = x; }
public override int GetHashCode() { return X; }
}

If you were to insert Foo's into a hashtable:

IDictionary d = new Hashtable();
Foo foo = new Foo(0);
d.Add(foo, 0);

You would (probably) expect :

Foo foo2 = new Foo(0);
object x = d[foo];
object y = d[foo2];

to both return a boxed 0, but they *dont* foo.GetHashCode() == 0 and
foo2.GetHashCode() == 0, but !Equals(foo, foo2).

So you need to redefine Equals:

public override bool Equals(object other) {
return ((Foo)other).X == X;
}

To do comparison by value, instead of reference.
--
Helge
Nov 16 '05 #4
Thank you Helge :))

Best Regards,
Stoyan

"Helge Jensen" wrote:
Stoyan wrote:
Hi All,
I don't understand very well this part of MSDN:
"Derived classes that override GetHashCode must also override Equals to
guarantee that two objects considered equal have the same hash code;
otherwise, Hashtable might not work correctly."


For hashtables to operate, the following must be true:

Equals(x,y) -> x.GetHashCode() == y.GetHashCode()
x.GetHashCode() != y.GetHashCode() -> !Equals(x,y)

This effectivly joins the partitioning that Equals imposes on objects
into larger sets, which rather neatly are numbered..., ready to put in
an index'ed array. Cunning thing, hashing :)

The above makes a constraint on how you can re-define GetHashCode
without redefining Equals.

Stricly speaking, if you use (keep the default) reference-equality the
only constraint on GetHashCode is that it is consistent:

x == y -> x.GetHashCode(x) == y.GetHashCode(y).
Does any one know, why we must also override Equals,


Well, strictly speaking... it's not required, but...
Please give my an example:)


In short, Hashtables usually does linear comparison, using Equals, of
the lookup key with every entry with the same hash-value modulo the size
of the hashtable. This also shows why choosing a hash-function with good
distribution is very important.

For hashing to be *usefull*, one usually calculates the hashcode on the
basis of the *value* of an object, not the reference, and *that's* why
you need to override Equals.

A minimalistic example:

class Foo {
public readonly int X;
public Foo(int x) { this.X = x; }
public override int GetHashCode() { return X; }
}

If you were to insert Foo's into a hashtable:

IDictionary d = new Hashtable();
Foo foo = new Foo(0);
d.Add(foo, 0);

You would (probably) expect :

Foo foo2 = new Foo(0);
object x = d[foo];
object y = d[foo2];

to both return a boxed 0, but they *dont* foo.GetHashCode() == 0 and
foo2.GetHashCode() == 0, but !Equals(foo, foo2).

So you need to redefine Equals:

public override bool Equals(object other) {
return ((Foo)other).X == X;
}

To do comparison by value, instead of reference.
--
Helge

Nov 16 '05 #5
as far as I know, one of the reasons that you should override Equals is that
might require that different objects (different references of the same type)
can be equal
so, based on your example :

public class SomeType
{
public override int GetHashCode()
{ return 1;}

int _field = 3;
}

if two instances of SomeType are equal (cause _field equals), you should
override Equals
--
http://www.xenopz.com
"Stoyan" <St****@discussions.microsoft.com> wrote in message
news:5B**********************************@microsof t.com...
Hi Bart,
I understand very well, if I override Equals, I must override and
GetHashCode() method.
but I don't understand for example:
I have two classes:
public class SomeType
{
public override int GetHashCode()
{ return 1;}
}
public class AnotherType
{
public override int GetHashCode()
{ return 1;}
}

SomeType a = new SomeType();
AnotherType b = new AnotherType();
Hashtable tbl = new Hashtable();
tbl.Add(a,a);
tbl.Add(b,b);
object a = tbl[a]; // this object is correct (SomeType)
object b = tbl[b]; // this object is correct (AnotherType)

In my case, why must also override Equals()?
I know, if hashcodes are different, Hashtable working better(faster)

Regards,
Stoyan

"Bart De Boeck" wrote:
Hi Stoyan,

The Hashtable type requires that if two objects are equal, they must
have
the same hash code value : when a key/value pair is added to a Hashtable,
the Hashtable uses the hash code of the key to determine the bucket that
stores the key. The bucket is then searched for a key which Equals the
given key (there might be more than one key in the bucket). If you wonder
why Equals is needed to find the key in the bucket : hashes can collide
(i.e. two different objects might generate the same hash - a hash
collision).
http://samples.gotdotnet.com/quickst...hashtable.aspx

Regards,
Bart

--
http://www.xenopz.com
"Stoyan" <St****@discussions.microsoft.com> wrote in message
news:FF**********************************@microsof t.com...
> Hi All,
> I don't understand very well this part of MSDN:
> "Derived classes that override GetHashCode must also override Equals to
> guarantee that two objects considered equal have the same hash code;
> otherwise, Hashtable might not work correctly."
> Does any one know, why we must also override Equals,
> Please give my an example:)
>
> Thanks,
> Stoyan


Nov 16 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Bill Mittenzwey | last post by:
Ok, I've read in the docs, some books and some articles by prominant dotneters about how to override GetHashCode, but it still leaves me somewhat puzzled. I have a custom object which I want to...
7
by: Avin Patel | last post by:
Hi I have question for GetHashCode() function, Is it correct in following code or there is more efficient way to implement GetHashCode() function class IntArray public int data public...
2
by: Mark | last post by:
I've built a class and overroad the Equals method. I've gotten the warning below. I'm unfamiliar with the "GetHashCode" method. An explantion of the method and its relation to the warning would...
7
by: AWHK | last post by:
How can I force anyone who subclasses my class to override the ToString() method? Andreas :-)
4
by: Andrew Robinson | last post by:
I have a class that has three properties: two of type int and one of type string. Is this the best method when overriding the GetHashCode() ? I am guessing not... any thing better? public...
5
by: taumuon | last post by:
I've got an object, Person, that supports IEquatable<Person>. It implements bool Equals(Person obj) as well as overriding bool Equals(object obj) I've got a container type that holds a member...
8
by: Ashish Khandelwal | last post by:
-----See below code, string str = "blair"; string strValue = "ABC"; string str1 = "brainlessness"; string strValue1 = "XYZ"; int hash = str.GetHashCode() ; // Returns 175803953 int hash1 =...
28
by: Tony Johansson | last post by:
Hello! I can't figure out what point it is to use GetHashCode. I know that this GetHashCode is used for obtaining a unique integer value. Can somebody give me an example that prove the...
6
by: =?Utf-8?B?RXRoYW4gU3RyYXVzcw==?= | last post by:
Hi, I have a moderately complex class (about 10 different string and int type fields along with two different List<stringfields). I want to override Equals(), so I need to override GetHashCode()....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...

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.