KeyValuePair<TKey, TValue>
Struct
System.Collections.Generic
Represents a key/value pair that can be returned by a dictionary.
Summary
The KeyValuePair<TKey, TValue>
structure is a simple immutable type that holds a key and its corresponding value. It is commonly used as the return type of the enumerator for dictionaries (like Dictionary<TKey, TValue>
), providing access to individual elements within the collection.
Syntax
public struct KeyValuePair<TKey, TValue> : IEquatable<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
KeyValuePair(TKey key, TValue value)
Initializes a new instance of the KeyValuePair<TKey, TValue>
structure with the specified key and value.
Properties
Key
Gets the key of the key/value pair.
Value
Gets the value of the key/value pair.
Methods
Equals(object other)
Determines whether the specified object is equal to the current object.
Equals(KeyValuePair<TKey, TValue> other)
Determines whether the specified KeyValuePair<TKey, TValue>
is equal to the current KeyValuePair<TKey, TValue>
.
GetHashCode()
Returns the hash code for the current instance.
ToString()
Returns a string representation of the current object.
Operators
Equality operator ==
Compares two KeyValuePair<TKey, TValue>
structures for equality.
Inequality operator !=
Compares two KeyValuePair<TKey, TValue>
structures for inequality.
Example
Using KeyValuePair with a Dictionary
The following example demonstrates how to iterate through a Dictionary<string, int>
and access its key-value pairs using KeyValuePair<TKey, TValue>
.
using System; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> ages = new Dictionary<string, int>(); ages.Add("Alice", 30); ages.Add("Bob", 25); ages.Add("Charlie", 35); Console.WriteLine("Dictionary Contents:"); foreach (KeyValuePair<string, int> pair in ages) { Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}"); } } }