Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a new value to Hashtable without using the Add method

Tags:

c#

.net

hashtable

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?

like image 767
stovroz Avatar asked Mar 25 '09 16:03

stovroz


2 Answers

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.
like image 70
Jon Skeet Avatar answered Sep 21 '22 20:09

Jon Skeet


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

like image 33
Sergej Andrejev Avatar answered Sep 21 '22 20:09

Sergej Andrejev