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 is highly efficient for key-based lookups, making it a go-to collection for many scenarios.

๐Ÿ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

๐Ÿ” Navigation

๐Ÿ’ฌ Feedback
๐Ÿš€ Start Learning
Share:

Tags: