What is a Dictionary<TKey, TValue>?
π‘ Concept: Dictionary<TKey, TValue> in C#
A Dictionary<TKey, TValue>
is a generic collection in C# that lets you store and quickly retrieve values based on unique keys.
π Quick Intro
If youβve ever needed a βphone bookβ style data structure β something where you look up information by a unique key β thatβs what Dictionary
is built for.
It gives you fast lookups, inserts, and deletions using hashing under the hood.
π§ Analogy
Imagine a real-world dictionary: the word you search for is the key,
and the definition you find is the value.
Just like flipping through a book, the C# Dictionary
helps you find values quickly using the key.
π§ Technical Breakdown
- π Keys are unique β you canβt add duplicates.
- π¦ Values can repeat β multiple keys can point to the same value.
- β‘ Backed by hashing for O(1) average lookups.
- π Defined in
System.Collections.Generic
. - π οΈ Provides methods like
Add
,Remove
,ContainsKey
. - π Performs faster than older collections like
Hashtable
because itβs type-safe.
π― Common Use Cases
- β Lookup tables (e.g., country codes β country names)
- β Caching results for quick reuse
- β Storing config or settings by name
- β Any scenario where key-based retrieval is faster than scanning a list
π» Code Example
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Alice"] = 30;
ages["Bob"] = 25;
foreach (var kvp in ages) {
Console.WriteLine($""{kvp.Key}: {kvp.Value}"");
}
}
}

β Interview Q&A
Q1: What is Dictionary<TKey, TValue>?
A: A collection of key-value pairs.
Q2: Can keys be duplicated?
A: No, keys must be unique.
Q3: What is hashing?
A: A technique for fast data retrieval.
Q4: What namespace contains Dictionary?
A: System.Collections.Generic.
Q5: How to add items?
A: Use Add or indexer.
Q6: Can values be duplicated?
A: Yes.
Q7: How to check if a key exists?
A: Use ContainsKey method.
Q8: How to remove items?
A: Use Remove method.
Q9: Is Dictionary thread-safe?
A: No, synchronization needed.
Q10: Can Dictionary be serialized?
A: Yes.
π MCQs
Q1. What is Dictionary<TKey, TValue>?
- List
- Key-value pair collection
- Array
- Queue
Q2. Can keys be duplicated?
- Yes
- No
- Maybe
- Sometimes
Q3. What is hashing?
- Slow data retrieval
- Fast data retrieval
- Sorting
- Searching
Q4. Namespace for Dictionary?
- System.IO
- System.Collections.Generic
- System.Text
- System.Threading
Q5. How to add items?
- Remove
- Add or indexer
- Clear
- Update
Q6. Can values be duplicated?
- No
- Yes
- Sometimes
- Never
Q7. How to check key existence?
- ContainsValue
- ContainsKey
- Exists
- HasKey
Q8. How to remove items?
- Delete
- Remove method
- Clear
- Dispose
Q9. Is Dictionary thread-safe?
- Yes
- No
- Sometimes
- Always
Q10. Can Dictionary be serialized?
- No
- Yes
- Sometimes
- Never
π‘ Bonus Insight
Dictionary
π PDF Download
Need a handy summary for your notes? Download this topic as a PDF!