What is a Dictionary<TKey, TValue>?
๐ก Concept: Dictionary<TKey, TValue> in C#
Dictionary<TKey, TValue> is a generic collection that stores key-value pairs with fast lookup based on keys.
๐ Quick Intro
The Dictionary provides an efficient way to map keys to values, useful for caching, lookup tables, and fast retrieval.
๐ง Analogy
Think of a Dictionary as a real-world dictionary where a word (key) maps to its definition (value).
๐ง Technical Explanation
- ๐ Keys are unique; values can be duplicated.
- โ๏ธ Uses hashing for fast key-based retrieval.
- ๐ Part of System.Collections.Generic namespace.
- ๐ ๏ธ Supports adding, removing, and searching key-value pairs.
- ๐ก Offers better performance than non-generic Hashtable.
๐ฏ Use Cases
- โ Lookup tables.
- โ Caching data with keys.
- โ Storing configuration settings.
- โ Implementing dictionaries and maps.
๐ป 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!