← Back to C# Course | Chapter 9: Collections | Lesson 3 of 7

Dictionary<K,V>

A Dictionary looks up values by a key, like finding a word in a dictionary or a name in a phone book. Each key points quickly to its value.

In this page:

  1. Dictionary<K,V>
Syntax
csharp
Dictionary<KeyType, ValueType> dictName = new Dictionary<KeyType, ValueType>();
dictName[key] = value;
ValueType value = dictName[key];
dictName.ContainsKey(key);

Dictionary<K,V>

Dictionary<TKey, TValue> stores key-value pairs and gives near-constant-time lookup by key. Keys must be unique; adding a duplicate key throws an exception unless you use the indexer to overwrite it.

It's the go-to collection whenever you need to look values up by a meaningful identifier rather than a position.

Warning: Accessing a missing key with dict[key] throws a KeyNotFoundException — use TryGetValue to check safely.

Example: Dictionary<K,V>

markup
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> ages = new Dictionary<string, int>
        {
            { "Alice", 30 },
            { "Bob", 25 },
        };

        ages["Cara"] = 40;

        if (ages.TryGetValue("Bob", out int bobAge))
        {
            Console.WriteLine(bobAge);
        }

        foreach (KeyValuePair<string, int> pair in ages)
        {
            Console.WriteLine($"{pair.Key}: {pair.Value}");
        }
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Reading a missing key with dict[key], which throws KeyNotFoundException; use TryGetValue.
  2. Adding a key that already exists with Add, which throws ArgumentException.
  3. Using a mutable object as a key and changing it after adding, so it can no longer be found.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.