Dictionary in C#

Last Updated : 3 Oct, 2026

Dictionary in C# is a generic collection that stores key-value pairs. The working of Dictionary is quite similar to the non-generic hashtable. It's a generic type, which is defined under System.Collections.Generic namespace. It's dynamic in nature, meaning the size of the dictionary is growing as needed.

  • The value is stored in the Key-Value pair.
  • It provides fast lookups for values based on keys.
  • Stores keys uniquely and adding duplicate keys results in a runtime exception.

Example: Creating and Displaying a Dictionary

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

class Geeks
{
    public static void Main()
    {
        // Creating a dictionary
        Dictionary<int, string> sub = new Dictionary<int, string>();

        // Adding elements
        sub.Add(1, "C#");
        sub.Add(2, "Javascript");
        sub.Add(3, "Dart");

        // Displaying dictionary
        foreach (var ele in sub){
            Console.WriteLine($"Key: {ele.Key}, Value: {ele.Value}");
        }
    }
}

Output
Key: 1, Value: C#
Key: 2, Value: Javascript
Key: 3, Value: Dart

Declaration of Dictionary

In C#, a Dictionary is declared by specifying the types of its keys and values.

Syntax

Dictionary dictionaryName = new Dictionary();

Parameters

  • TKey: Specifies the type of keys in the dictionary.
  • TValue: Specifies the type of values in the dictionary.

Example:

Dictionary students = new Dictionary();

Here, int is the key type and string is the value type.

Note: Each element in a Dictionary is represented as a KeyValuePair, which contains one key and its associated value.

Hierarchy of Dictionary

The Dictionary class directly inherits from the Object class and implements several generic and non-generic collection interfaces.

file

Constructors of Dictionary Class

The Dictionary class provides constructors for creating an empty dictionary, specifying an initial capacity, copying elements from another dictionary, and using a custom key comparer.

1. Dictionary()

Creates an empty Dictionary using the default equality comparer for the key type.

Dictionary students = new Dictionary();

2. Dictionary(int)

Creates an empty dictionary with the specified initial capacity.

Dictionary students = new Dictionary(10);

Here, 10 specifies the initial capacity of the dictionary.

3. Dictionary(IEqualityComparer)

Creates an empty dictionary that uses the specified equality comparer to compare keys.

Dictionary students =
new Dictionary(StringComparer.OrdinalIgnoreCase);

Here, StringComparer.OrdinalIgnoreCase makes key comparison case-insensitive.

4. Dictionary(IDictionary)

Creates a new dictionary containing the key-value pairs copied from the specified dictionary.

Dictionary students = new Dictionary
{
{ 1, "Amit" },
{ 2, "Rahul" }
};
Dictionary copy = new Dictionary(students);

5. Dictionary(int, IEqualityComparer)

Creates an empty dictionary with the specified initial capacity and key comparer.

Dictionary students =
new Dictionary( 10, StringComparer.OrdinalIgnoreCase);

6. Dictionary(IDictionary, IEqualityComparer)

Creates a new dictionary by copying key-value pairs from an existing dictionary and using the specified key comparer.

Dictionary students =
new Dictionary
{
{ "Amit", 101 },
{ "Rahul", 102 }
};

Dictionary copy =
new Dictionary(
students,
StringComparer.OrdinalIgnoreCase);

Properties of Dictionary

The Dictionary class provides properties for accessing keys, values, the number of elements, and individual values.

PropertyDescription
ComparerGets the IEqualityComparer that is used to determine equality of keys in the dictionary.
CountGets the number of key-value pairs contained in the Dictionary.
Item[TKey]Gets or sets the value associated with the specified key.
KeysGets a collection containing the keys in the Dictionary.
ValuesGets a collection containing the values in the Dictionary.

Example: The following example demonstrates commonly used properties.

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

class Geeks
{
    public static void Main()
    {
        Dictionary<int, string> students = new Dictionary<int, string>
        {
            { 1, "Amit" },
            { 2, "Rahul" },
            { 3, "Priya" }
        };

        Console.WriteLine("Count: " + students.Count);
        Console.WriteLine("Value: " + students[1]);

        Console.WriteLine("Keys:");
        foreach (int key in students.Keys)
        {
            Console.WriteLine(key);
        }

        Console.WriteLine("Values:");
        foreach (string value in students.Values)
        {
            Console.WriteLine(value);
        }
    }
}

Output
Count: 3
Value: Amit
Keys:
1
2
3
Values:
Amit
Rahul
Priya

Methods of Dictionary Class

The Dictionary class provides methods for adding, accessing, searching, updating, and removing key-value pairs.

MethodDescription
Add(TKey, TValue)Adds the specified key and value to the dictionary.
Clear()Removes all keys and values from the dictionary.
ContainsKey(TKey)Determines whether the dictionary contains the specified key.
ContainsValue(TValue)Determines whether the dictionary contains the specified value.
GetEnumerator()Returns an enumerator that iterates through the key-value pairs in the dictionary.
Remove(TKey)Removes the key-value pair associated with the specified key from the dictionary.
Remove(TKey, out TValue)Removes the value associated with the specified key and returns the removed value.
TryAdd(TKey, TValue)Attempts to add the specified key and value to the dictionary.
TryGetValue(TKey, out TValue)Attempts to get the value associated with the specified key.

Performing Different Operations on Dictionary

The Dictionary class supports several operations for managing key-value pairs, such as adding, accessing, updating, searching, and removing elements.

1. Adding Elements

There are three common ways to add elements to a Dictionary:

  • Add(TKey, TValue): Adds a key-value pair to the dictionary. The specified key must be unique.
  • Collection Initializer: Allows multiple key-value pairs to be added when creating the dictionary.
  • Indexer: Adds a key-value pair by assigning a value to a specified key.

Example:

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

class Geeks
{
    public static void Main()
    {
        // Using Add()
        Dictionary<int, string> dict = new Dictionary<int, string>();
        dict.Add(1, "One");
        dict.Add(2, "Two");

        // Using indexer
        dict[3] = "Three";

        // Display elements
        foreach (var pair in dict)
        {
            Console.WriteLine("Key: " + pair.Key + ", Value: " + pair.Value);
        }
    }
}

Output
Key: 1, Value: One
Key: 2, Value: Two
Key: 3, Value: Three

Note: If Add() is used with an existing key, it throws an ArgumentException. Using the indexer with an existing key updates its value.

2. Accessing Elements

Elements in a Dictionary can be accessed using a key or by iterating through its key-value pairs.

Using Indexer

The indexer is used to retrieve the value associated with a specified key.

Dictionary dict = new Dictionary
{
{ 1, "One" },
{ 2, "Two" }
};

Note: If the specified key does not exist, accessing it through the indexer throws a KeyNotFoundException.

Using foreach Loop

The foreach loop is used to iterate through all key-value pairs in the dictionary.

foreach (KeyValuePair pair in dict)
{
    Console.WriteLine("Key: " + pair.Key + ", Value: " + pair.Value);
}

Using TryGetValue()

The TryGetValue() method attempts to retrieve the value associated with a specified key and indicates whether the key exists.

if (dict.TryGetValue(1, out string value))
{
    Console.WriteLine("Value: " + value);
}

Note: TryGetValue() returns true if the specified key exists and retrieves its value through the out parameter. Otherwise, it returns false.

3. Updating Elements

The indexer is used to update the value associated with an existing key in the Dictionary.

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

class Geeks
{
    public static void Main()
    {
        Dictionary<int, string> dict = new Dictionary<int, string>
        {
            { 1, "One" },
            { 2, "Two" }
        };

        // Update the value associated with key 1
        dict[1] = "Updated One";

        Console.WriteLine(dict[1]);
    }
}

Output
Updated One

4. Removing Elements

The Dictionary class provides two main methods for removing elements:

  • Remove(TKey): Removes the key-value pair associated with the specified key.
  • Clear(): Removes all key-value pairs from the dictionary.

Example:

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

class Geeks
{
    public static void Main()
    {
        Dictionary<int, string> dict = new Dictionary<int, string>
        {
            { 1, "One" },
            { 2, "Two" },
            { 3, "Three" }
        };

        // Remove the key-value pair with key 2
        dict.Remove(2);

        Console.WriteLine("After Remove():");

        foreach (var pair in dict)
        {
            Console.WriteLine("Key: " + pair.Key + ", Value: " + pair.Value);
        }

        // Remove all elements
        dict.Clear();

        Console.WriteLine("Count after Clear(): " + dict.Count);
    }
}

Output
After Remove():
Key: 1, Value: One
Key: 3, Value: Three
Count after Clear(): 0

5. Checking Elements

The Dictionary class provides methods to check whether a key or value exists.

Example:

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

class Geeks
{
    public static void Main()
    {
        Dictionary<int, string> dict = new Dictionary<int, string>
        {
            { 1, "One" },
            { 2, "Two" },
            { 3, "Three" }
        };

        // Check whether a key exists
        Console.WriteLine(dict.ContainsKey(2));

        // Check whether a value exists
        Console.WriteLine(dict.ContainsValue("Three"));
    }
}

Output
True
True
Comment

Explore