tags:

views:

275

answers:

3

To add a new value to a dotnet Hashtable I've always used:

myHashtable.Add(myNewKey, myNewValue);

but I've just come across some code which does the following instead:

myHashTable[myNewKey] = myNewValue;

Is there any difference between the two methods?

+3  A: 

first will throw exception if there already were an item with given key and the second will throw an exception if there was no item with such key

Sergej Andrejev
+12  A: 

To correct Sergej's answer a little...

  • Add will indeed throw an exception if the key already exists.
  • Using the indexer as a setter won't throw an exception (unless you specify a null key).
  • Using the indexer as a getter will throw an exception if the key doesn't exist and if you're using a generic IDictionary<TKey,TValue>. In the non-generic IDictionary implementations (e.g. Hashtable) you'll get a null reference. You can't use a null key for either one though - you'll get an ArgumentNullException.
Jon Skeet
Much obliged. Cheers!
A: 

The difference is in handling duplicate values.

myHashtable.Add() throws ArgumentException if HashTable already contains element with your key. myHashTable[myNewKey] replaces old value with new one.

Hldev Zkran