I recently came across a situation where the properties of a class were adding the value to an internal dictionary of key value pairs which made it easy to loop through and return a JSON string. This worked great until we later ran into a situation where we needed to update a property after it had already been set, which of course generated a "System.ArgumentException: An item with the same key has already been added". While it is easy enough to add a check to see if the dictionary already contains the key you are attempting to add, doing this for every property would be way too much code repetition so an Extension Method seemed appropriate.
Add the following extenstion method to a static class in your solution, then add that namespace to the list of namespaces you are "using" at the top of any class that might need it, and your Dictionary will have a .AddOrUpdate(key, value) method:
public static IDictionary<TKey,TValue> AddOrUpdate<TKey,TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
if(dictionary.ContainsKey(key))
{
dictionary[key] = value;
}
else
{
dictionary.Add(key, value);
}
return dictionary;
}