Search code examples
c#dictionarycontainskey

Method to add new or update existing item in C# Dictionary


In some legacy code I have seen the following extension method to facilitate adding a new key-value item or updating an existing value:

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, Method-1 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!
Has this difference been eliminated in C# > 3.0 versions?

The objective of this method is too not throw an exception if the user sends the same key-value again. The method should, if the key is:

  • found — update the key's value, and
  • not found — create a new key-value.

Solution

  • 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.