Hashtable Key objects

  • Thread starter Thread starter Wamiq Ansari
  • Start date Start date
W

Wamiq Ansari

Hi,

I am using a System.Windows.Forms.Label object as key in my Hashtable. One
thing that has surprised me is that if I create two Label objects with same
properties (ie. Name, TabIndex,Text,Size,Dock) and use them as Key in my
Hashtable it doesn't give any error.

I thought, generally, in a Hashtable we cannot use two same objects as keys.
The Label Objects in this case are being created in a loop and used as keys
in a Hashtable.

Can anyone please shed some light on this.

Regards,

Wamiq Ansari
(e-mail address removed)
 
Wamiq,

By default, the hash of value types is based on the contents of the
structure, so creating a new structure, setting the values to the same
thing, and then using that as a hash will give you what you wanted.

However, for reference types, by default, the hashcode is based on the
reference equality, which is why you are seeing what you are seeing.

You have some options here. First, you can provide your own hash code
provider, and not use the GetHashCode implementation on the Label class
(which defers to Object.GetHashCode anyways), or, you could create a
structure that has the properties of the label you want to use as your key.

Hope this helps.
 
Hi, Wamiq

it should not surprise you, because when you create 2 objects they are
different, even if seemingly properties are same. You can see that by trying
if(label1==label2) and checking result.
Or you can check that label1.Handle!=label2.Handle.

I would suggest to check chapter on reference types in C# Language Reference
to get all the details.

HTH
Alex
 
Back
Top