Dictionary<TKey, TValue>::IDictionary::Add Method (Object^, Object^)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Adds the specified key and value to the dictionary.

Namespace:   System.Collections.Generic
Assembly:  mscorlib (in mscorlib.dll)

virtual void Add(
	Object^ key,
	Object^ value
) sealed = IDictionary::Add


Type: System::Object^

The object to use as the key.

Type: System::Object^

The object to use as the value.

Exception Condition

key is null.


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 IDictionary::Add method to add some elements. The example demonstrates that the IDictionary::Add 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.

No code example is currently available or this language may not be supported.

Universal Windows Platform
Available since 8
.NET Framework
Available since 2.0
Portable Class Library
Supported in: portable .NET platforms
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top