Groups | Blog | Home
all groups > c# > january 2005 >

c# : System.Collections.Hashtable.Add question


nzanella NO[at]SPAM gmail.com
1/28/2005 11:46:44 PM

Hello,

I cannot seem to find this in the MSDN documentation: what I would
like to ask is whether the System.Collections.Hashtable.Add should
throw an exception or replace the old value when an element with
the same key value as an existing one is added. For instance, is
the following code legal in C#?

hashtable.Add("aaa", "foo");
hashtable.Add("aaa", "bar");

Thanks,

Good night,

Neil
Vijaye Raji
1/29/2005 12:53:19 AM
Why don't you write it and find it for yourself?

-vJ

[quoted text, click to view]

Francois Bonin [C# MVP]
1/29/2005 10:14:18 AM
An exception will be thrown. The type will be ArgumentException.

This info is available in the MSDN documentation.

[quoted text, click to view]

Jon Skeet [C# MVP]
1/29/2005 2:32:42 PM
[quoted text, click to view]

From the docs for Add:

<quote>
The Item property can also be used to add new elements by setting the
value of a key that does not exist in the Hashtable. For example:
myCollection["myNonexistentKey"] = myValue. However, if the specified
key already exists in the Hashtable, setting the Item property
overwrites the old value. In contrast, the Add method does not modify
existing elements.
</quote>

and under Exceptions:

<quote>
ArgumentException An element with the same key already exists
in the Hashtable.
</quote>

So, if you want an exception, use Add. If you don't, use the indexer.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
AddThis Social Bookmark Button