IDictionary(TKey, TValue) Interface
Represents a generic collection of key/value pairs.
Assembly: mscorlib (in mscorlib.dll)
The IDictionary(TKey, TValue) interface is the base interface for generic collections of key/value pairs.
Each element is a key/value pair stored in a KeyValuePair(TKey, TValue) object.
Each pair must have a unique key. Implementations can vary in whether they allow key to be a null reference (Nothing in Visual Basic). The value can be a null reference (Nothing in Visual Basic) and does not have to be unique. The IDictionary(TKey, TValue) interface allows the contained keys and values to be enumerated, but it does not imply any particular sort order.
The foreach statement of the C# language (For Each in Visual Basic, for each in C++) requires the type of each element in the collection. Since each element of the 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:
The foreach statement is a wrapper around the enumerator, which only allows reading from, not writing to, the collection.
Note: |
|---|
Because keys can be inherited and their behavior changed, their absolute uniqueness cannot be guaranteed by comparisons using the Equals method. |
The implementing class must have a means to compare keys.
The following code example creates an empty Dictionary(TKey, TValue) of strings, with integer keys, and accesses it through the IDictionary(TKey, TValue) interface.
The code example uses the Add method to add some elements. The example demonstrates that the Add method throws ArgumentException when attempting to add a duplicate key.
The example uses the Item property (the indexer in C#) to retrieve values, demonstrating that a KeyNotFoundException is thrown when a requested key is not present, and showing that the value associated with a key can be replaced.
The example shows how to use the TryGetValue method as a more efficient way to retrieve values if a program often must try key values that are not in the dictionary, and how to use the ContainsKey method to test whether a key exists prior to calling the Add method.
Finally, the example shows how to enumerate the keys and values in the dictionary, and how to enumerate the values alone using the Values property.
Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune
The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Note: