C# Dictionary

Beginner
7 min read
Updated: Nov 2026
3 examples
Dictionary

Definition and Usage

In C#, Dictionary<TKey,TValue> is a collection that stores pairs: a key and the value that belongs to it. Think of a phone book. You look up a name (the key) and get a number (the value). You add pairs with Add(), read them with TryGetValue(), and delete them with Remove().

Every key must be unique, but values may repeat. A dictionary finds a value from its key in about O(1) time, which is much faster than scanning a list. It lives in the System.Collections.Generic namespace, so add using System.Collections.Generic; at the top of your file.

The Dictionary Methods index lists every method guide in this series.

Do not rely on order.

A Dictionary often returns pairs in the order you added them, but that is not guaranteed. When you need a fixed order, sort the keys or use SortedDictionary.

C# Syntax

Common first steps:

C#
using System.Collections.Generic;

Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Asha", 25);           // add a new pair
ages["Ravi"] = 31;              // indexer: add or overwrite
int a = ages["Asha"];           // read (throws if the key is missing)
bool ok = ages.TryGetValue("Zed", out int z);   // read safely
int total = ages.Count;         // number of pairs

Dictionary vs List and Array

Pick the collection that matches how you will look things up:

TypeYou find items byGood for
Dictionary<TKey,TValue>Key (a name, an id, a code)Lookups, counters, caches, settings
List<T>Position (0, 1, 2) or by searchingAn ordered list that grows and shrinks
T[] (array)Position (0, 1, 2)A fixed number of items

Indexer, Add, TryAdd, and TryGetValue

These four are the ones beginners use most. They behave differently when the key exists or is missing:

CallKey is newKey already exists / missing
d[key] = valueAdds the pairOverwrites the old value
Add()Adds the pairThrows ArgumentException
TryAdd()Adds the pair, returns trueKeeps the old value, returns false
TryGetValue()(reading) returns true and the valueMissing key: returns false, no exception

C# Examples

Example 1 — Create a Dictionary and Read It

A first program that stores three names with their ages, then reads one value by its key.

C#
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        Dictionary<string, int> ages = new Dictionary<string, int> {
            { "Asha", 25 },
            { "Ravi", 31 },
            { "Meena", 28 }
        };

        Console.WriteLine(ages["Ravi"]);
        Console.WriteLine(ages.Count);
        Console.WriteLine(ages.ContainsKey("Meena"));
    }
}

How It Works

  1. Type with two parts. Dictionary<string, int> means the keys are string and the values are int.
  2. Collection initializer. Each { "Asha", 25 } in the braces adds one key and value pair when the dictionary is created.
  3. Read by key. ages["Ravi"] jumps straight to the value 31 without looking at the other pairs.
  4. Size and membership. Count says how many pairs there are, and ContainsKey says whether a name is stored.

Example 2 — Write and Read in Different Ways

Use the indexer to write, TryAdd to add only new keys, and TryGetValue to read safely.

C#
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        Dictionary<string, int> stock = new Dictionary<string, int>();

        stock["apple"] = 10;
        stock["apple"] = 12;
        Console.WriteLine(stock["apple"]);

        Console.WriteLine(stock.TryAdd("apple", 99));
        Console.WriteLine(stock.TryAdd("pear", 5));

        if (stock.TryGetValue("mango", out int mango)) {
            Console.WriteLine(mango);
        } else {
            Console.WriteLine("No mango");
        }
    }
}

How It Works

  1. Indexer adds. The first stock["apple"] = 10 creates the pair, because the key is new.
  2. Indexer overwrites. The second assignment replaces 10 with 12, so reading stock["apple"] prints 12.
  3. TryAdd tells you. "apple" exists, so the result is False and the value stays 12. "pear" is new, so its result is True.
  4. Safe read. "mango" is missing, so TryGetValue returns false and the else branch prints a message instead of throwing.

Example 3 — Dictionary Lookup vs Searching an Array

Find Ravi's age with two parallel arrays, then with a dictionary, and compare the code.

C#
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        string[] names = { "Asha", "Ravi", "Meena" };
        int[] ages = { 25, 31, 28 };

        int pos = Array.IndexOf(names, "Ravi");
        Console.WriteLine(ages[pos]);

        Dictionary<string, int> map = new Dictionary<string, int>();
        for (int i = 0; i < names.Length; i++) {
            map[names[i]] = ages[i];
        }

        Console.WriteLine(map["Ravi"]);
        Console.WriteLine(map.Count);
    }
}

How It Works

  1. Array way. Array.IndexOf scans the names from the start until it finds "Ravi", then the position is used in the second array.
  2. Two arrays to keep in step. If only one array is sorted or edited, names and ages no longer match.
  3. Build the dictionary. The loop stores each name as a key and its age as the value, so the link between them is built in.
  4. Dictionary way. map["Ravi"] finds the value from the key directly. Both ways print 31, and Count is 3.

Next: C# Dictionary Methods Index

After you know what a Dictionary is for, open the method index for a full tutorial on each Dictionary API.

Start withWhy
Add()Put a new key and value pair into the dictionary
TryGetValue()Read a value safely, without exceptions
ContainsKey()Check whether a key exists
Remove()Delete a pair by key

Full list: C# Dictionary Methods index (/c-sharp/dictionary/method).

Frequently Asked Questions

It is a collection of key and value pairs in System.Collections.Generic. Each key is unique, and you use the key to find its value very quickly.
A List stores items by position (0, 1, 2) and you search it item by item. A Dictionary stores pairs by key and finds a value directly from its key.
No. Add throws ArgumentException for a repeated key, TryAdd returns false, and the indexer overwrites the old value. Values may repeat.
You should not rely on any order. It often returns pairs in the order they were added, but that is not guaranteed. Use SortedDictionary if you need sorted keys.
Open the C# Dictionary Methods index. It lists Add, TryAdd, ContainsKey, ContainsValue, TryGetValue, Remove, Clear, EnsureCapacity, TrimExcess, and GetEnumerator.

Browse every Dictionary method

Open the methods index for categorized guides with examples and FAQs.

Dictionary Methods Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful