There is a Add(TKey key, TValue value) method but it throws if using a key that is already in use.
Adding AddOrUpdate(TKey key, TValue value) will simply use an existing key or add it.
Simply to be more clear and avoid boilerplate code and possibly an unnecessary lookup.
PR coming soon as it's fairly trivial.
Isn't it what the indexer does?
Maybe, do you have a link reference?
Ah yes, I suppose what I'm advocating is to avoid having to use that syntax. Instead the simple update would look something like this:
public static void AddOrUpdate<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
dictionary[key] = value;
}
//usage
var dictionary = new Dictionary<string, string>();
dictionary.Add("myKey", "someValue");//succeeds
dictionary.Add("myKey", "someValue");//duplicate key exception
dictionary.AddOrUpdate("myKey", "someValue");//succeeds
dictionary.AddOrUpdate("myKey", "someValue2");//succeeds
_Note: that I'm using it as an extension method at present._
I'll hold on the PR for now.
I second the request for AddOrUpdate. The Indexer does the same thing but you can't pass indexers as Funcs and such. I'd also request a GetOrAdd method similar to what ConcurrentDictiony has.
Related discussion: https://github.com/dotnet/corefx/issues/31126
To match the shape of ConcurrentDictionary the return type should be TValue.