IDictionary<TKey, TValue>::Add Method (TKey, TValue)
Adds an element with the provided key and value to the IDictionary<TKey, TValue>.
Assembly: mscorlib (in mscorlib.dll)
| Exception | Condition |
|---|---|
| ArgumentNullException | key is nullptr. |
| ArgumentException | An element with the same key already exists in the IDictionary<TKey, TValue>. |
| NotSupportedException | The IDictionary<TKey, TValue> is read-only. |
You can also use the Item property to add new elements by setting the value of a key that does not exist in the dictionary; for example, myCollection["myNonexistentKey"] = myValue in C# (myCollection("myNonexistentKey") = myValue in Visual Basic). However, if the specified key already exists in the dictionary, setting the Item property overwrites the old value. In contrast, the Add method does not modify existing elements.
Implementations can vary in how they determine equality of objects; for example, the List<T> class uses Comparer<T>::Default, whereas the Dictionary<TKey, TValue> class allows the user to specify the IComparer<T> implementation to use for comparing keys.
Implementations can vary in whether they allow key to be nullptr.
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 an ArgumentException when attempting to add a duplicate key.
This code is part of a larger example that can be compiled and executed. See System.Collections.Generic::IDictionary<TKey, TValue>.
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.