C# Interview Question #126

What is the difference between Dictionary<TKey,TValue> and ConcurrentDictionary<TKey,TValue>?

Advanced LINQ, Expressions & Collections Senior Advanced

Quick Interview Answer

Dictionary<TKey,TValue> is a general-purpose key-value collection and is not designed for unsynchronized concurrent writes.

Detailed Explanation

Dictionary<TKey,TValue> is a general-purpose key-value collection and is not designed for unsynchronized concurrent writes.

ConcurrentDictionary<TKey,TValue> is designed for multi-threaded access and provides atomic operations such as GetOrAdd, AddOrUpdate, TryAdd, and TryRemove.

Using a ConcurrentDictionary does not automatically make compound logic outside the collection atomic. Developers should prefer its atomic APIs instead of performing separate ContainsKey and assignment operations that can race.

Code Example

var cache = new ConcurrentDictionary<int, string>();

string value = cache.GetOrAdd(
    10,
    id => $"Product-{id}");