473,836 Members | 1,372 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 9609
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****@discuss ions.microsoft. com> wrote in message
news:FF******** *************** ***********@mic rosoft.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****@discuss ions.microsoft. com> wrote in message
news:FF******** *************** ***********@mic rosoft.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.GetHashCod e() == 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.GetHashCod e() == 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****@discuss ions.microsoft. com> wrote in message
news:5B******** *************** ***********@mic rosoft.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****@discuss ions.microsoft. com> wrote in message
news:FF******** *************** ***********@mic rosoft.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
6652
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 be able to have sorted correctly in a sortedlist/hashtable... For that to work correctly, I need to override Equals(). Fair enough, otherwise the sort would not really know what represents the value of my object. Then the compiler tells me that I...
7
6576
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 override int GetHashCode() int hash = 0 for (int i = 0; i < data.Length; i++
2
9589
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 be appreciated. warning: 'myClass' overrides Object.Equals(object o) but does not override Object.GetHashCode() Thanks in advance. Mark
7
4565
by: AWHK | last post by:
How can I force anyone who subclasses my class to override the ToString() method? Andreas :-)
4
392
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 override int GetHashCode() { string hash = craneCounterweightID.ToString() + ":" + trailerID.ToString() + ":" + craneConfigurationTypeCode; return hash.GetHashCode();
5
2393
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 object of generic type T, that supports IEquatable<T>, and a method, DoComparisons(T obj) to compare the member object to the object passed in.
8
5870
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 = str1.GetHashCode(); // Returns 175803953 Hashtable ht = new Hashtable(); ht.Add(hash ,strValue); ht.Add(hash1,strValue1); // ****ERROR****
28
3791
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 usefulness of this GetHashCode or it it of no use at all? A mean that if I get an integer from current time in some way what should I use it for?
6
8245
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(). The standard override for GetHashCode() for something would be to join GetHashCode for each field with ^ (XOR). Right? But, in this case, one of the fields is a "Unique" Identifier and SHOULD uniquely identify the instance of the class. If that is...
0
9825
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10859
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10560
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10602
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9388
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6984
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5653
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5829
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3116
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.