Dictionary(TKey, TValue).IDictionary.Add Method
Adds the specified key and value to the dictionary.
Assembly: mscorlib (in mscorlib.dll)
key is a null reference (Nothing in Visual Basic).
key is of a type that is not assignable to the key type TKey of the Dictionary(TKey, TValue).
value is of a type that is not assignable to TValue, the type of values in the Dictionary(TKey, TValue).
A value with the same key already exists in the Dictionary(TKey, TValue).
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. However, if the specified key already exists in the dictionary, setting the Item property overwrites the old value. In contrast, the Add method throws an exception if the specified key already exists.
If Count is less than the capacity, this method approaches an O(1) operation. If the capacity needs to be increased to accommodate the new element, this method becomes an O(n) operation, where n is Count.
The following code example shows how to access the Dictionary(TKey, TValue) class through the System.Collections.IDictionary interface. The code example creates an empty Dictionary(TKey, TValue) of strings with string keys and uses the method to add some elements. The example demonstrates that the method throws an ArgumentException when attempting to add a duplicate key, or when a key or value of the wrong data type is supplied.
The code example demonstrates the use of several other members of the System.Collections.IDictionary interface.
Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.