Looking at the ConcurrentDictionary documentation it says the following:
Represents a thread-safe collection of key/value pairs that can be accessed by multiple threads concurrently.
Now when reading this it makes me think that I can call any method in the ConcurrentDictionary API and it will be thread safe...but it this meant to include explicit implementations aswell, do I have that guarantee?
My example is if I want an atomic operation to remove an item from a ConcurrentDictionary if its value is some value.
So I can do this:
var concurrentDictionary = new ConcurrentDictionary<string, string>();
concurrentDictionary.TryAdd("hey", "ho");
((ICollection<KeyValuePair<string, string>>) concurrentDictionary).Remove(new KeyValuePair<string, string>("hey", "ho"));
Now I have looked in the source code and that operation is both atomic and thread safe, but does the fact that its not on the ConcurrentDictionary API mean that I shouldn't use it...or maybe that I am using the collection to do something I shouldn't be doing with it.
I can take it one step further and write the following extension method:
public static boolean TryRemove(this ICollection<KeyValuePair<TKey, TValue>> collection, TKey key, TValue value)
{
return collection.Remove(new KeyValuePair<TKey, TValue>(key, value));
}
This will appear in Intellisense for ConcurrentDictionary because it implements the ICollection interface and many developers may not even know anything is untoward (if anything actually is?!)
EDIT: What I mean by "implicitly documented" is that ConcurrentDictionary implements a set of interfaces. It's documentation says that its thread safe but doesn't state if its only for the methods listed on that page but implies that all operations on an instance would be safe.