.NET API Documentation

Dictionary<TKey,TValue> Class

The Dictionary class provides a collection of keys and values. Implements IDictionary, IReadOnlyDictionary, and many other interfaces.

Namespace

System.Collections.Generic

Assembly

System.Collections.dll

Syntax

public class Dictionary<TKey,TValue> : IDictionary<TKey,TValue>, …

Type Parameters

Inheritance Hierarchy

Object
 └─Dictionary<TKey,TValue>

Constructors

Dictionary()
Dictionary(Int32)
Dictionary(IEqualityComparer<TKey>)
public Dictionary();

Initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the default initial capacity, and uses the default equality comparer for the key type.

public Dictionary(int capacity);

Initializes a new instance with the specified capacity.

public Dictionary(IEqualityComparer<TKey> comparer);

Initializes a new instance that uses the specified IEqualityComparer<TKey>.

Properties

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

Methods

Add
ContainsKey
TryGetValue
Remove
public void Add(TKey key, TValue value);

Adds the specified key and value to the dictionary.

public bool ContainsKey(TKey key);

Determines whether the dictionary contains the specified key.

public bool TryGetValue(TKey key, out TValue value);

Gets the value associated with the specified key.

public bool Remove(TKey key);

Removes the element with the specified key.

Example

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var ages = new Dictionary<string, int>();
        ages["Alice"] = 30;
        ages["Bob"] = 25;
        ages.Add("Charlie", 35);

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

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