when is hashcode used?

S

Saurabh

Hello All,

I have been facing this bizarre problem within a combobox having a list of
UK postcodes. When I assign the SelectedItem propoerty of the combobox, a
completely different item was actually selected in the combobox. I broke
into the code at the assignment statement and then looked at the values for
different items in the watch window. It looked something like this :

postcodeObj : EH11 1LQ
comboBox1.SelectedIndex = -1 (nothing currently selected)
comboBox1.Items.IndexOf(postcodeObj) : 1614
comboBox1.Items[1614].ToString() : EH11 1LA (something different to what i
am intending to set as selected item)

I also found out that my item was at the location 1621 in the combobox
items.

The combobox is no sorted, and I couldn't figure out what was going wrong
here, till I added 2 more things in the watch window
comboBox1.Items[1614].GetHashCode( )
comboBox1.Items[1621].GetHashCode( )

These 2 values appeared to be same, Now I remember that I have overriden the
GetHashCode() method in my postcode object to return a hashcode, it creates
a hashcode based on the postcode string and one more attribute. (XOR the
number and the hashcode of the string)

My question is, Is hashcode used internally by the 'SelectedItem' set
method? Is there any way for me to get round this problem? I have the
postcode strings and a unique number, Can I generate a unique hashcode from
this combination? I don't want the number to be my hashcode.

TIA,

--Saurabh
 
L

Lloyd Dupont

I believe internaly they used Equals().
You can generate hashcode the way you like, but hascode are mostly relevant
with immutable object.
 
S

Saurabh

Aaaaaaah, so it means if I override Equals( ), thats where I need to see
whats going wrong.
Thanks for the tip,

--Saurabh
 

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

Top