Dictionary<TKey,TValue> Class

Overview

Represents a collection of keys and values. A Dictionary provides fast lookups by key. The type parameter TKey represents the type of keys in the dictionary, and TValue represents the type of values.

Namespace

System.Collections.Generic

Assembly

System.Collections.dll

Syntax

public class Dictionary<TKey,TValue> : IDictionary<TKey,TValue>, 
                                         IDictionary,
                                         IReadOnlyDictionary<TKey,TValue>,
                                         ISerializable,
                                         IDeserializationCallback
    where TKey : notnull

Type Parameters

ParameterDescription
TKeyThe type of keys in the dictionary. Must be non‑nullable.
TValueThe type of values in the dictionary.

Constructors

Dictionary()

Initializes a new empty dictionary.

var dict = new Dictionary<string,int>();
Dictionary(int capacity)

Initializes a new dictionary with the specified initial capacity.

var dict = new Dictionary<string,int>(capacity: 100);
Dictionary(IDictionary<TKey,TValue> dictionary)

Initializes a new dictionary that contains elements copied from the specified dictionary.

var source = new Dictionary<string,int> { ["a"]=1, ["b"]=2 };
var dict = new Dictionary<string,int>(source);

Properties

NameTypeDescription
CountintGets the number of key/value pairs contained in the dictionary.
KeysICollection<TKey>Gets a collection containing the keys in the dictionary.
ValuesICollection<TValue>Gets a collection containing the values in the dictionary.
Item[TKey key]TValueGets or sets the value associated with the specified key.
ComparerIEqualityComparer<TKey>Gets the equality comparer used to compare keys.

Methods

Add(TKey key, TValue value)

Adds the specified key and value to the dictionary.

dict.Add("apple", 5);
ContainsKey(TKey key)

Determines whether the dictionary contains the specified key.

bool hasApple = dict.ContainsKey("apple");
TryGetValue(TKey key, out TValue value)

Gets the value associated with the specified key, if present.

if (dict.TryGetValue("banana", out int qty))
{
    Console.WriteLine($"Bananas: {qty}");
}
Remove(TKey key)

Removes the element with the specified key from the dictionary.

dict.Remove("apple");
Clear()

Removes all keys and values from the dictionary.

dict.Clear();
GetEnumerator()

Returns an enumerator that iterates through the dictionary.

foreach (var kvp in dict)
{
    Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}

Examples

// Create a dictionary of employee IDs and names
var employees = new Dictionary<int,string>
{
    [101] = "Alice",
    [102] = "Bob",
    [103] = "Charlie"
};

// Update an entry
employees[102] = "Robert";

// Iterate
foreach (var (id, name) in employees)
{
    Console.WriteLine($"ID {id}: {name}");
}

// Check existence
if (employees.TryGetValue(104, out var unknown))
{
    Console.WriteLine(unknown);
}
else
{
    Console.WriteLine("Employee 104 not found.");
}