I was just wondering how it was possible that ConcurrentDictionary does not have an Add method which is visible in the Visual Studio IDE. I only seem to get the TryX Methods
They are discouraging the use of the Add
method because the method throws an exception if the key is already present in the dictionary. For most dictionaries, the developer can write code in a way to guarantee that the exception will not be thrown under any normal scenario. However, to perform this operation (Contains
followed by Add
) with a concurrent dictionary, you would need to use exclusive locks in methods accessing the dictionary, which defeats the entire purpose of a concurrent dictionary.
TryAdd
combines the Contains
and Add
checks without requiring you to lock the dictionary, and allows you to once again write code that won't throw an exception in normal scenarios.
That's because of explicit interface implementation. See http://msdn.microsoft.com/en-us/library/aa288461(v=vs.71).aspx