CKTIS / C#
KeyValuePair<TKey,TValue> — a key-value pair
KeyValuePair<TKey,TValue> holds one key and one value of specified types. Its Key and Value properties are read-only; you encounter this type, for example, when iterating over Dictionary<TKey,TValue>.
Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification
Syntax
new KeyValuePair<TKey,TValue>(key, value)
pair.Key
pair.ValueKeyValuePair<TKey,TValue> is a structure in the System.Collections.Generic namespace. It represents a single pair, not an entire dictionary. TKey specifies the key type, and TValue specifies the value type. Iterating over Dictionary<TKey,TValue> yields elements of this pair type.
The constructor new KeyValuePair<TKey,TValue>(key, value) accepts a key and a value. Read them through Key and Value. Both properties have only a get accessor, so assigning pair.Value = 4 is a compile-time error.
To replace the pair held in a variable, assign a new instance to that variable. This differs from changing a property of the existing pair. In the example, the second assignment replaces the entire pair while retaining the same key.
This explanation and example cover APIs available in .NET 10. The project setting LangVersion=preview does not mean that the type itself is an experimental language feature.
Examples
using System;
using System.Collections.Generic;
internal static class Program
{
private static void Main()
{
var pair = new KeyValuePair<string, int>("apples", 3);
Console.WriteLine($"{pair.Key}: {pair.Value}");
pair = new KeyValuePair<string, int>(pair.Key, 4);
Console.WriteLine($"{pair.Key}: {pair.Value}");
}
}Result
apples: 3 apples: 4
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.