C# ยท Chapter 24 of 46

C# Dictionary

A Dictionary<TKey, TValue> stores data as key-value pairs, letting you look up a value quickly using its unique key instead of a numeric index.

Dictionaries are ideal for scenarios like storing a phone book (name โ†’ number) or counting word occurrences (word โ†’ count), where you need fast lookups by a meaningful identifier.

Syntax
Dictionary<TKey, TValue> name = new Dictionary<TKey, TValue>();
name[key] = value;

Creating and using a Dictionary

A Dictionary is declared with two type parameters: the key type and value type, like `Dictionary<string, int> ages = new Dictionary<string, int>();`. Use square brackets to add or access values by key.

Checking and looping

ContainsKey() checks if a key exists before accessing it to avoid errors. You can loop through a dictionary with foreach, getting each item as a KeyValuePair.

Example 1 (csharp)
using System;
using System.Collections.Generic;

class Program {
  static void Main() {
    Dictionary<string, int> ages = new Dictionary<string, int>();
    ages["Amy"] = 25;
    ages["Bob"] = 30;
    Console.WriteLine(ages["Amy"]);
  }
}
Output
25

The value 25 is stored under the key "Amy" and retrieved using square brackets.

Example 2 (csharp)
using System;
using System.Collections.Generic;

class Program {
  static void Main() {
    Dictionary<string, int> ages = new Dictionary<string, int> { { "Amy", 25 }, { "Bob", 30 } };
    foreach (KeyValuePair<string, int> pair in ages) {
      Console.WriteLine(pair.Key + ": " + pair.Value);
    }
  }
}
Output
Amy: 25
Bob: 30

foreach iterates over each key-value pair in the dictionary.

Key points

  • Dictionary<TKey, TValue> stores key-value pairs.
  • Keys must be unique within a dictionary.
  • ContainsKey() safely checks if a key exists before accessing it.
  • foreach with KeyValuePair<TKey, TValue> iterates over all entries.
๐Ÿ’ก Note: Accessing a key that doesn't exist with [] throws a KeyNotFoundException โ€” use TryGetValue() for safer lookups.

๐Ÿ“ Quick Quiz

1. What does a Dictionary store?

2. What happens if you try to add a duplicate key?

3. Which method safely checks if a key exists?