473,797 Members | 2,893 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

GetHashCode() does not work as expected

I am trying to look for change in an instanciated object that contains a
generic list<>. I first get an int value of objA.GetHashCod e(). I add a few
objects to the list<collection in objA I compared the initial value with
the current hash code of objA and they were still the same. OK I thought
maybe if I compare the internal collections I would be more successful, so I
overrode the GetHashCode() method with the hashcode of the List. Still the
values are the same.

1) Am I missing how hashcode should be working?

2) What I'm trying to do is compare collections, so I'm trying to see if
there have been any changes to the collection to determine if I have to
perform an expensive operation. Is there a better way to do this?

TIA
-- Abe
Dec 31 '06 #1
3 1812
AbeR wrote:
I am trying to look for change in an instanciated object that contains a
generic list<>. I first get an int value of objA.GetHashCod e(). I add a few
objects to the list<collection in objA I compared the initial value with
the current hash code of objA and they were still the same. OK I thought
maybe if I compare the internal collections I would be more successful, so I
overrode the GetHashCode() method with the hashcode of the List. Still the
values are the same.

1) Am I missing how hashcode should be working?
Unfortunately, yes. Generally, with mutable reference types,
GetHashCode() isn't overridden to do anything interesting based on the
instance's fields. To understand why, consider this sample code:

// add an object reference to a hash table
MyReferenceObje ct inst = new MyReferenceObje ct();
inst.SomeField = 2001;

Hashtable tab = new Hashtable();
tab[inst] = 12345; // [1]

// now change the object
inst.SomeField = 1965;

// and try to retrieve the value
Console.WriteLi ne("Stored integer is {0}", tab[inst]); // [2]

Because Hashtable uses the key's hash code to know where to store and
find the value, if inst.GetHashCod e() were to change between lines [1]
and [2], the Hashtable wouldn't be able to find the correct value -
even though the key you're using to search in line [2] is exactly the
same key you used to add in line [1], and it's still identical to the
key stored inside the Hashtable.

This isn't an issue with value types (or immutable reference types like
String), because you can't change the copy that's stored inside the
hash table.
2) What I'm trying to do is compare collections, so I'm trying to see if
there have been any changes to the collection to determine if I have to
perform an expensive operation. Is there a better way to do this?
I'd suggest writing a new collection class, a wrapper around List<>
that raises an event or updates a counter with each change.

Jesse

Dec 31 '06 #2
Thanks for the quick response. Back to the drawing board.

Happy New Year ;-)
-- Abe

"Jesse McGrew" wrote:
AbeR wrote:
I am trying to look for change in an instanciated object that contains a
generic list<>. I first get an int value of objA.GetHashCod e(). I add a few
objects to the list<collection in objA I compared the initial value with
the current hash code of objA and they were still the same. OK I thought
maybe if I compare the internal collections I would be more successful, so I
overrode the GetHashCode() method with the hashcode of the List. Still the
values are the same.

1) Am I missing how hashcode should be working?

Unfortunately, yes. Generally, with mutable reference types,
GetHashCode() isn't overridden to do anything interesting based on the
instance's fields. To understand why, consider this sample code:

// add an object reference to a hash table
MyReferenceObje ct inst = new MyReferenceObje ct();
inst.SomeField = 2001;

Hashtable tab = new Hashtable();
tab[inst] = 12345; // [1]

// now change the object
inst.SomeField = 1965;

// and try to retrieve the value
Console.WriteLi ne("Stored integer is {0}", tab[inst]); // [2]

Because Hashtable uses the key's hash code to know where to store and
find the value, if inst.GetHashCod e() were to change between lines [1]
and [2], the Hashtable wouldn't be able to find the correct value -
even though the key you're using to search in line [2] is exactly the
same key you used to add in line [1], and it's still identical to the
key stored inside the Hashtable.

This isn't an issue with value types (or immutable reference types like
String), because you can't change the copy that's stored inside the
hash table.
2) What I'm trying to do is compare collections, so I'm trying to see if
there have been any changes to the collection to determine if I have to
perform an expensive operation. Is there a better way to do this?

I'd suggest writing a new collection class, a wrapper around List<>
that raises an event or updates a counter with each change.

Jesse

Dec 31 '06 #3
2) What I'm trying to do is compare collections, so I'm trying to see
if
there have been any changes to the collection to determine if I have to
perform an expensive operation. Is there a better way to do this?

I'd suggest writing a new collection class, a wrapper around List<>
that raises an event or updates a counter with each change.
Yes, a serial number generally will be the best way to do this. Might as
well implement lockless synchronization at the same time, because the serial
number plays an important role there as well.
>>
Jesse


Jan 1 '07 #4

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++
5
9606
by: Stoyan | last post by:
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
8
9912
by: Matthias Kientz | last post by:
I have a class which should override the GetHashcode() function, which look like this: public class A { public string str1; public string str2; //other methods...
2
2378
by: One Handed Man [ OHM# ] | last post by:
The help for the .NET Framework Class Library tells us that the Object.GetHashCode() Method does not guarantee uniqueness' or consistency and that overriding this and the Equals method is a good idea. It also tells us that using the XOR functions on two or more Fields or Properties is an acceptable way to achieve this. What do you guys think is the best approach to this given that generating a hashcode should be fast as well as consistant....
1
2205
by: MariusI | last post by:
I have some business objects which overrides Equals to provide syntax equality instead of just reference equality. Overriding equals gives me a warning that i must override GetHashcode(). Msdn says this about implementing hashcode: (1)If two objects of the same type represent the same value, the hash function must return the same constant value for either object. (2)For the best performance, a hash function must generate a random...
5
2285
by: Metaman | last post by:
I'm trying to write a generic method to generate Hashcodes but am having some problems with (generic) collections. Here is the code of my method: public static int GetHashCode(object input) { try { Type objectType = input.GetType(); PropertyInfo properties = objectType.GetProperties();
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
3789
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?
0
9685
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
10468
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
10245
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...
0
9063
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
6802
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
5458
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...
1
4131
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3748
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2933
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.