First of all, is it safe to simply add an item to a concurrent dictionary using the indexed assignment (e.g. myConcurrentDictionary[someKey] = someValue;
)?
I'm just confused because it hides the IDictionary methods (e.g. Add
).
Why does AddOrUpdate() require a func to update the value? Is there a method to set the value for a key regardless of whether the key already exists?
I couldn't really gather this from the MSDN page.
Yes, using the indexer should be absolutely fine if you want to add or replace a value.
AddOrUpdate
takes a delegate so that you can merge the "old" and "new" value together to form the value you want to be in the dictionary. If you don't care about the old value, use the indexer instead.
The indexer is the way to "set the value for a key regardless of whether the key already exists" just as in any other IDictionary<,>
implementation.
The documentation has a neat section at the bottom - a sort of recipe bit - including this:
To do this...
Store a key/value pair in the dictionary unconditionally, and overwrite the value of a key that already existsUse this method
The indexer’s setter:dictionary[key] = newValue
So it's officially sanctioned.