System.Collections.Hashtable.Add question

  • Thread starter Thread starter nzanella
  • Start date Start date
N

nzanella

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
 
An exception will be thrown. The type will be ArgumentException.

This info is available in the MSDN documentation.
 
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");

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.
 
Back
Top