Microsoft Learn

Interface

Interface IKeyValuePair<TKey, TValue>

Represents a key/value pair that can be returned by a dictionary or a collection that returns its elements as key/value pairs.

public interface IKeyValuePair<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.

Members

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

Remarks

The IKeyValuePair<TKey, TValue> interface is used to represent an entry in a collection that maps keys to values. For example, when you iterate over a IDictionary<TKey, TValue>, each element you get is an IKeyValuePair<TKey, TValue>.

This interface provides simple read-only access to the key and value components of a pair.

Example

using System; using System.Collections.Generic; public class Example { public static void Main() { // Create a dictionary Dictionary<string, int> ages = new Dictionary<string, int> { { "Alice", 30 }, { "Bob", 25 }, { "Charlie", 35 } }; // Iterate through the dictionary using IKeyValuePair Console.WriteLine("Iterating through the dictionary:"); foreach (KeyValuePair<string, int> pair in ages) { Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}"); } // Accessing individual components of a KeyValuePair if (ages.TryGetFirstValue("Bob", out int bobAge)) { Console.WriteLine($"\nBob's age is: {bobAge}"); } } // Helper extension method for demonstration (not part of the standard library) public static bool TryGetFirstValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, out TValue value) { if (dictionary.TryGetValue(key, out value)) { return true; } return false; } }

Requirements

Namespace: System.Collections.Generic

Assembly: mscorlib.dll (in .NET Framework), System.Runtime.dll (in .NET Core / .NET 5+)