How do you set a value in a ConcurrentDictionary regardless of whether it contains the Key

user2434174 picture user2434174 · Feb 5, 2014 · Viewed 11.8k times · Source

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.

Answer

Jon Skeet picture Jon Skeet · Feb 5, 2014
  1. Yes, using the indexer should be absolutely fine if you want to add or replace a value.

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

  3. 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 exists

Use this method
The indexer’s setter: dictionary[key] = newValue

So it's officially sanctioned.