Dictionary<TKey, TValue> maps keys to values with fast lookup—like HashMap in Java or dicts in Python. HashSet<T> stores unique elements with set operations.
Dictionary usage
var counts = new Dictionary<string, int>();
counts["apple"] = 3;
if (counts.TryGetValue("apple", out int n)) {
Console.WriteLine(n);
}
Prefer TryGetValue over double indexing when the key might be missing—avoids two hash lookups.
HashSet
var tags = new HashSet<string> { "csharp", "dotnet" };
tags.Add("csharp"); // ignored duplicate
Important interview questions and answers
- Q: Dictionary vs List?
A: Dictionary keyed lookup O(1) average; List is ordered by index—scan for keys is O(n). - Q: HashSet vs List for uniqueness?
A: HashSet enforces uniqueness with hash-based membership tests.
Self-check
- What method safely reads a missing dictionary key?
- Does HashSet allow duplicates?
Pitfall: dict[key] throws if the key is missing—use TryGetValue or ContainsKey when insertion side effects are unwanted.
Interview prep
- Dictionary vs Hashtable?
Dictionary<TKey,TValue>is generic and type-safe; legacyHashtableboxes keys and values asobject.- TryGetValue vs indexer?
TryGetValueavoids exceptions and unwanted inserts;dict[key]throws when the key is missing.