Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Collections

KeyValuePair<TKey,TValue>

Reference for C# KeyValuePair<TKey,TValue>: the struct a Dictionary yields when enumerated, how to create and deconstruct pairs and when a tuple is better.

KeyValuePair<TKey,TValue> is a small immutable struct that holds one key and one value. You meet it most often when you enumerate a Dictionary<TKey,TValue>, because each element of the dictionary is a pair. You can also create pairs yourself, put them in a list, or pass them to methods such as Dictionary.Add overloads and Enumerable.ToDictionary.

Since .NET Core 2.0 a pair can be deconstructed with var (key, value) = pair, and KeyValuePair.Create(key, value) builds one with type inference.

C#
var pair = KeyValuePair.Create("age", 31);
var (key, value) = pair;

Try it

C# Create, read and deconstruct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Building and transforming dictionaries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public readonly struct KeyValuePair<TKey, TValue>
{
    public KeyValuePair(TKey key, TValue value);
    public TKey Key { get; }
    public TValue Value { get; }
    public void Deconstruct(out TKey key, out TValue value);
}

public static class KeyValuePair
{
    public static KeyValuePair<TKey, TValue> Create<TKey, TValue>(TKey key, TValue value);
}
Name Description
Key The key. Read-only.
Value The value. Read-only.
Create Builds a pair and lets the compiler infer both type arguments.

Returns: ToString() returns [key, value], with each part converted to text (an empty string for null).

Usage notes

  • A pair is immutable: you cannot assign pair.Value. To change what a dictionary stores, write dict[key] = newValue.
  • It is a value type, so copies are independent of the dictionary. After you change stock["apples"], a pair you took earlier still holds the old value.
  • The default pair has a null key (for reference key types) and a default value.
  • Keys in a Dictionary are unique; a List<KeyValuePair<,>> or IEnumerable<KeyValuePair<,>> can hold duplicates and has no lookup, so finding a key is O(n).
  • Choose a named tuple such as (string Name, int Qty) when you want meaningful property names; a pair always says Key and Value. Records are better when the data has a domain meaning.
  • KeyValuePair<TKey,TValue> is not related to DictionaryEntry (non-generic Hashtable) or to Lookup groupings.
  • Do not use a mutable object as a key: changing it after insertion breaks hash lookups.