Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

I think that you can try using TryAdd() or AddOrUpdate() method from ConcurrentDictionay, as you can see here.

http://msdn.microsoft.com/es-es/library/dd287191(v=vs.110).aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top