My question: Why is ConcurrentDictionary implemented like that?
I believe it's to encourage you to think of the concurrency implications - that multiple threads may be writing the same keys at the same time. Adding an existing key is therefore somewhat less likely to be a programming error, and should be considered carefully.
- If you want to overwrite unconditionally, use the indexer
- If you want to add or update, where the update can use the existing value, use
AddOrUpdate
- If you want to add if possible, but not overwrite any existing value, use
TryAdd
If you find yourself wanting the existing Add
behaviour frequently, you could always write your own extension method.