Manish Basantani Manish Basantani - 1 month ago 13
C# Question

Method to Add new or update existing item in Dictionary

In some legacy code i have see the following extension method to facilitate adding a new key-value item or updating the value, if the key already exists.

Method-1 (legacy code).

public static void CreateNewOrUpdateExisting<TKey, TValue>(
this IDictionary<TKey, TValue> map, TKey key, TValue value)
{
if (map.ContainsKey(key))
{
map[key] = value;
}
else
{
map.Add(key, value);
}
}


Though, I have checked that
map[key]=value
does exactly the same job. That is, this method could be replace with Method-2 below.

Method-2.

public static void CreateNewOrUpdateExisting<TKey, TValue>(
this IDictionary<TKey, TValue> map, TKey key, TValue value)
{
map[key] = value;
}


Now, my question is.. Could there be any problem if i replace Method-1 by Method-2? Will it break in any possible scenario?

Also, I think this used to be the difference between HashTable and Dictionary. HashTable allows updating an item, or adding a new item by using indexer while Dictionary does not!! Is this difference been eliminated in C# > 3.0 versions?

The objective of this method is not too throw exception if user sends the same key-value again, the method should just update the entry with the new value, and to make a new entry if new key-value pair has been send to the method.

Answer

Could there be any problem if i replace Method-1 by Method-2?

No, just use map[key] = value. The two options are equivalent.


Regarding Dictionary<> vs. Hashtable: When you start Reflector, you see that the indexer setters of both classes call this.Insert(key, value, /* add */ false); and the add parameter is responsible for throwing an exception, when inserting a duplicate key. So the behavior is the same for both classes.

Comments