If I have a ConcurrentDictionary
and want to use the Add()
function, I need to cast to IDictionary
:
var cd = new ConcurrentDictionary<int, int>();
cd.Add(1, 1); // Compile error: does not contain a definition for 'Add'
IDictionary<int, int> id = cd;
id.Add(1, 1); // Works
Question ConcurrentDictionary and IDictionary tells me it's because ConcurrentDictionary
implements IDictionary
explicitly, using private methods.
My question: Why is ConcurrentDictionary
implemented like that? What is the benefit of hiding the use of an implemented interface?
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.
AddOrUpdate
TryAdd
If you find yourself wanting the existing Add
behaviour frequently, you could always write your own extension method.
See more on this question at Stackoverflow