KeyValuePair<TKey,TValue> Struct

Definition

Defines a key/value pair that can be set or retrieved.

C#
public struct KeyValuePair<TKey,TValue>
C#
public readonly struct KeyValuePair<TKey,TValue>
C#
[System.Serializable]
public struct KeyValuePair<TKey,TValue>

Type Parameters

TKey

The type of the key.

TValue

The type of the value.

Inheritance
KeyValuePair<TKey,TValue>
Attributes

Examples

The following code example shows how to enumerate the keys and values in a dictionary, using the KeyValuePair<TKey,TValue> structure.

This code is part of a larger example provided for the Dictionary<TKey,TValue> class.

C#
// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
    Console.WriteLine("Key = {0}, Value = {1}",
        kvp.Key, kvp.Value);
}

Remarks

The Dictionary<TKey,TValue>.Enumerator.Current property returns an instance of this type.

The foreach statement of the C# language (for each in C++, For Each in Visual Basic) returns an object of the type of the elements in the collection. Since each element of a collection based on IDictionary<TKey,TValue> is a key/value pair, the element type is not the type of the key or the type of the value. Instead, the element type is KeyValuePair<TKey,TValue>. For example:

C#
foreach( KeyValuePair<string, string> kvp in myDictionary )
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}

The foreach statement is a wrapper around the enumerator, which allows only reading from, not writing to, the collection.

Constructors

KeyValuePair<TKey,TValue>(TKey, TValue)

Initializes a new instance of the KeyValuePair<TKey,TValue> structure with the specified key and value.

Properties

Key

Gets the key in the key/value pair.

Value

Gets the value in the key/value pair.

Methods

Deconstruct(TKey, TValue)

Deconstructs the current KeyValuePair<TKey,TValue>.

ToString()

Returns a string representation of the KeyValuePair<TKey,TValue>, using the string representations of the key and value.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

See also