Advertisement
Beginner C#, Collections

When should you use a Dictionary<TKey,TValue>?

Short answer

When you need fast key-based lookups (O(1) average). Keys are unique; use TryGetValue to avoid exceptions on missing keys.

Save C# mock interview
Advertisement
AModel answer
When you need fast key-based lookups (O(1) average). Keys are unique; use TryGetValue to avoid exceptions on missing keys.
var prices = new Dictionary<string,decimal>{["pen"]=1.5m};
if (prices.TryGetValue("pen", out var p)) { }
Real-world example
Caching users by Id or counting word frequencies.