Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
396 views
Welcome To Ask or Share your Answers For Others

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...