Update value against the same key in hashtable using C# code

There are two ways you can add data to your Hashtable as shown below:
ohashtable[Key1] = Value1;
ohashtable[Key2] =  Value2;
ohashtable[Key3] = Value3;

Or like this:
ohashtable.Add(Key1, Value1);
ohashtable.Add(Key2, Value2);
ohashtable.Add(Key3, Value3);

There is a difference between these two ways. 
Using Add method, you can't have update the value against existing Key. But you can, if you use the square brackets. 

For example,
ohashtable.Add(Key1, Value1);
ohashtable.Add(Key1, Value2); //this will throw exception at run time

Whereas,
ohashtable[Key1] = Value1;
ohashtable[Key1] =  Value2; // this will allow the entry in hashtable
It won't add a new key but will update the value against the existing key.

2 comments:

mayank said...

thnkx..

Kushal said...

thanks sir that blog help me lot

Post a Comment