Hashtable caveat

  • Thread starter Thread starter Duncan Bayne
  • Start date Start date
D

Duncan Bayne

Hi All,

Be careful when indexing Hashtable elements by number. The following
code will create two quite distinct entries in an Hashtable:

myHashtable.Add((int)666, "Foo");
myHashtable.Add((long)666, "Foo");

Always ensure all indexing is done by the objects of the same type -
it's probably safest to explicitly cast them.

Yours,
Duncan Bayne


--
+-----------------------------------------------------------------+
| Duncan Bayne phone (+64) 027 2536395 email (e-mail address removed) |
| ============ icq# 115621676 msn (e-mail address removed) |
| |
| web http://homepages.ihug.co.nz/~dhbayne/ |
| http://groups.yahoo.com/group/akl_airsoft/ |
| http://groups.yahoo.com/group/wakeup_nz/ |
+-----------------------------------------------------------------+
| "The ultimate result of shielding men from the effects of folly |
| is to fill the world with fools." |
| |
| - Herbert Spencer. |
+-----------------------------------------------------------------+
 
Duncan,

That's all because of the number 666 you've used for testing :-) Well, just
kidding. Hashtable uses a call to Equals to finally compare keys. While it
is obvious that there's an overload of Equals that accepts two integers or
two longs and compares them by value, Int32's Equals always returns false
when its argument is not of a type Int32.
 
Duncan,
Which is where in C# 2.0 (Whidbey) it will be "better" to use
System.Collections.Generic.Dictionary<K, V> as the key will be strongly
typed!

http://longhorn.msdn.microsoft.com/...lections.generic/c/dictionary/dictionary.aspx

Something like:

Dictionary<int, string> myHashTable = new Dictionary<int, string>();
myHashTable.Add(666, "Foo");
myHashTable.Add((long)666, "Foo"); // error! long does not fit in an
integer!

Also the above will be more efficient then HashTable as the key will not be
boxed!

Hope this helps
Jay
 
Back
Top