<$BlogRSDURL$>

A splat of all my blathering.

Wednesday, July 14, 2004

Not all keys are created equal 

Let's take a quick walk in the realm of things that are possibly reasonable but certainly not obvious.

Given the following code, what are the values of b1-b4?

  Hashtable h = new Hashtable();
  h.Add(1, 1);
  h.Add((uint)2, 1);
  bool b1 = h.ContainsKey(1);
  bool b2 = h.ContainsKey((uint)1);
  bool b3 = h.ContainsKey(2);
  bool b4 = h.ContainsKey((uint)2);

b1 is true
b2 is false
b3 is false
b4 is true

Furthermore, consider the following:

  object i = 5;
  object j = (uint)5;
  int h1 = i.GetHashCode();
  int h2 = j.GetHashCode();

The values of h1 and h2 are both 5. What gives?

Posted at 7/14/2004 12:53:00 PM |
Comments:
GetHashCode returns a key that you CAN use (but don't have to) in a HashTable.

In your first example, you use an Int32 as a key, then a UInt32. They are different objects, thus different keys.

In the second example, the GetHashCode() call for a UInt32 just casts the uint to an int, thus an equivalent key is used.

To get the behavior that you appear to want, do this:

Hashtable h = new Hashtable();
h.Add(1.GetHashCode(), 1);
h.Add(((uint)2).GetHashCode(), 1);
bool b1 = h.ContainsKey(1.GetHashCode());
bool b2 = h.ContainsKey(((uint)1).GetHashCode());
bool b3 = h.ContainsKey(2.GetHashCode());
bool b4 = h.ContainsKey(((uint)2).GetHashCode());

Scott Hanselman
 
Post a Comment

This page is powered by Blogger. Isn't yours?