KeyValuePair<TKey,TValue> Struct

Represents a key-value pair that can be returned by an IDictionary<TKey,TValue> or enumerated by a Dictionary<TKey,TValue>.

Syntax

public struct KeyValuePair<TKey,TValue>

Type Parameters

TKey
The type of the key in the key-value pair.
TValue
The type of the value in the key-value pair.

Constructors

Name Description
KeyValuePair<TKey,TValue> (TKey key, TValue value) Initializes a new instance of the KeyValuePair<TKey,TValue> structure.

Properties

Name Description
Key Gets the key of the key-value pair.
Value Gets the value of the key-value pair.

Methods

Name Description
CompareTo(object obj) Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position as the other object.
CompareTo(KeyValuePair<TKey,TValue> other) Compares the current instance with another KeyValuePair<TKey,TValue> of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position as the other object.
Equals(object obj) Determines whether the specified object is equal to the current instance.
Equals(KeyValuePair<TKey,TValue> other) Determines whether the specified KeyValuePair<TKey,TValue> is equal to the current instance.
GetHashCode() Returns the hash code for the current instance.
ToString() Returns a string representation of the KeyValuePair<TKey,TValue>.

Operators

Name Description
Equality (==) Compares two KeyValuePair<TKey,TValue> structures for equality.
Inequality (!=) Compares two KeyValuePair<TKey,TValue> structures for inequality.

Remarks

The KeyValuePair<TKey,TValue> structure is immutable. Once created, its Key and Value properties cannot be changed.

It is commonly used when iterating through a dictionary. For example:


using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        var cities = new Dictionary<string, string>()
        {
            { "UK", "London" },
            { "France", "Paris" },
            { "Japan", "Tokyo" }
        };

        foreach (KeyValuePair<string, string> kvp in cities)
        {
            Console.WriteLine($"Country: {kvp.Key}, Capital: {kvp.Value}");
        }
    }
}
                

Examples

Creating a KeyValuePair


var kvp = new KeyValuePair<int, string>(1, "Apple");
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
// Output: Key: 1, Value: Apple
                

Using KeyValuePair in a Dictionary


var dictionary = new Dictionary<string, int>();
dictionary.Add("One", 1);
dictionary.Add("Two", 2);

foreach (var item in dictionary)
{
    Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
// Output:
// Key: One, Value: 1
// Key: Two, Value: 2