Dictionary<TKey, TValue>.IDictionary.Add Method
Microsoft Silverlight will reach end of support after October 2021. Learn more.
Adds the specified key and value to the dictionary.
Namespace: System.Collections.Generic
Assembly: mscorlib (in mscorlib.dll)
Syntax
'Declaration
Private Sub Add ( _
key As Object, _
value As Object _
) Implements IDictionary.Add
void IDictionary.Add(
Object key,
Object value
)
Parameters
- key
Type: System.Object
The object to use as the key.
- value
Type: System.Object
The object to use as the value.
Implements
Exceptions
Exception | Condition |
---|---|
ArgumentNullException | key is nulla null reference (Nothing in Visual Basic). |
ArgumentException | key is of a type that is not assignable to the key type TKey of the Dictionary<TKey, TValue>. -or- value is of a type that is not assignable to TValue, the type of values in the Dictionary<TKey, TValue>. -or- A value with the same key already exists in the Dictionary<TKey, TValue>. |
Remarks
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.
Examples
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.
Imports System.Collections
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
' Create a new dictionary of strings, with string keys,
' and access it using the IDictionary interface.
'
Dim openWith As IDictionary = _
New Dictionary(Of String, String)
' Add some elements to the dictionary. There are no
' duplicate keys, but some of the values are duplicates.
' IDictionary.Add throws an exception if incorrect types
' are supplied for key or value.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
Try
openWith.Add(42, New Example())
Catch ex As ArgumentException
outputBlock.Text &= "An exception was caught for " & _
"IDictionary.Add. Exception message:" & vbLf _
& vbTab & ex.Message & vbLf & vbCrLf
End Try
' The Add method throws an exception if the new key is
' already in the dictionary.
Try
openWith.Add("txt", "winword.exe")
Catch
outputBlock.Text &= "An element with Key = ""txt"" already exists." & vbCrLf
End Try
' The Item property is the default property, so you
' can omit its name when accessing elements.
outputBlock.Text &= String.Format("For key = ""rtf"", value = {0}.", _
openWith("rtf")) & vbCrLf
' The default Item property can be used to change the value
' associated with a key.
openWith("rtf") = "winword.exe"
outputBlock.Text &= String.Format("For key = ""rtf"", value = {0}.", _
openWith("rtf")) & vbCrLf
' If a key does not exist, setting the default Item property
' for that key adds a new key/value pair.
openWith("doc") = "winword.exe"
' The default Item property returns Nothing if the key
' is of the wrong data type.
outputBlock.Text &= String.Format("The default Item property returns Nothing" _
& " if the key is of the wrong type:") & vbCrLf
outputBlock.Text &= String.Format("For key = 2, value = {0}.", _
openWith(2)) & vbCrLf
' The default Item property throws an exception when setting
' a value if the key is of the wrong data type.
Try
openWith(2) = "This does not get added."
Catch
outputBlock.Text &= String.Format("A key of the wrong type was specified" _
& " when setting the default Item property.") & vbCrLf
End Try
' Unlike the default Item property on the Dictionary class
' itself, IDictionary.Item does not throw an exception
' if the requested key is not in the dictionary.
outputBlock.Text &= String.Format("For key = ""tif"", value = {0}.", _
openWith("tif")) & vbCrLf
' Contains can be used to test keys before inserting
' them.
If Not openWith.Contains("ht") Then
openWith.Add("ht", "hypertrm.exe")
outputBlock.Text &= String.Format("Value added for key = ""ht"": {0}", _
openWith("ht")) & vbCrLf
End If
' IDictionary.Contains returns False if the wrong data
' type is supplied.
outputBlock.Text &= String.Format("openWith.Contains(29.7) returns {0}", _
openWith.Contains(29.7))
' When you use foreach to enumerate dictionary elements
' with the IDictionary interface, the elements are retrieved
' as DictionaryEntry objects instead of KeyValuePair objects.
outputBlock.Text &= vbCrLf
For Each de As DictionaryEntry In openWith
outputBlock.Text &= String.Format("Key = {0}, Value = {1}", _
de.Key, de.Value) & vbCrLf
Next
' To get the values alone, use the Values property.
Dim icoll As ICollection = openWith.Values
' The elements of the collection are strongly typed
' with the type that was specified for dictionary values,
' even though the ICollection interface is not strongly
' typed.
outputBlock.Text &= vbCrLf
For Each s As String In icoll
outputBlock.Text &= String.Format("Value = {0}", s) & vbCrLf
Next s
' To get the keys alone, use the Keys property.
icoll = openWith.Keys
' The elements of the collection are strongly typed
' with the type that was specified for dictionary keys,
' even though the ICollection interface is not strongly
' typed.
outputBlock.Text &= vbCrLf
For Each s As String In icoll
outputBlock.Text &= String.Format("Key = {0}", s) & vbCrLf
Next s
' Use the Remove method to remove a key/value pair. No
' exception is thrown if the wrong data type is supplied.
outputBlock.Text &= vbLf + "Remove(""dib"")" & vbCrLf
openWith.Remove("dib")
If Not openWith.Contains("dib") Then
outputBlock.Text &= "Key ""dib"" is not found." & vbCrLf
End If
End Sub
End Class
' This code example produces the following output:
'
'An exception was caught for IDictionary.Add. Exception message:
' The value "42" is not of type "System.String" and cannot be used in this generic collection.
'Parameter name: key
'
'An element with Key = "txt" already exists.
'For key = "rtf", value = wordpad.exe.
'For key = "rtf", value = winword.exe.
'The default Item property returns Nothing if the key is of the wrong type:
'For key = 2, value = .
'A key of the wrong type was specified when setting the default Item property.
'For key = "tif", value = .
'Value added for key = "ht": hypertrm.exe
'openWith.Contains(29.7) returns False
'
'Key = txt, Value = notepad.exe
'Key = bmp, Value = paint.exe
'Key = dib, Value = paint.exe
'Key = rtf, Value = winword.exe
'Key = doc, Value = winword.exe
'Key = ht, Value = hypertrm.exe
'
'Value = notepad.exe
'Value = paint.exe
'Value = paint.exe
'Value = winword.exe
'Value = winword.exe
'Value = hypertrm.exe
'
'Key = txt
'Key = bmp
'Key = dib
'Key = rtf
'Key = doc
'Key = ht
'
'Remove("dib")
'Key "dib" is not found.
'
using System;
using System.Collections;
using System.Collections.Generic;
public class Example
{
public static void Demo(System.Windows.Controls.TextBlock outputBlock)
{
// Create a new dictionary of strings, with string keys,
// and access it using the IDictionary interface.
//
IDictionary openWith = new Dictionary<string, string>();
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
// IDictionary.Add throws an exception if incorrect types
// are supplied for key or value.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
try
{
openWith.Add(42, new Example());
}
catch (ArgumentException ex)
{
outputBlock.Text += String.Format("An exception was caught for " +
"IDictionary.Add. Exception message:\n\t{0}\n",
ex.Message) + "\n";
}
// The Add method throws an exception if the new key is
// already in the dictionary.
try
{
openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
outputBlock.Text += "An element with Key = \"txt\" already exists." + "\n";
}
// The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
outputBlock.Text += String.Format("For key = \"rtf\", value = {0}.",
openWith["rtf"]) + "\n";
// The indexer can be used to change the value associated
// with a key.
openWith["rtf"] = "winword.exe";
outputBlock.Text += String.Format("For key = \"rtf\", value = {0}.",
openWith["rtf"]) + "\n";
// If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
openWith["doc"] = "winword.exe";
// The indexer returns null if the key is of the wrong data
// type.
outputBlock.Text += String.Format("The indexer returns null"
+ " if the key is of the wrong type:") + "\n";
outputBlock.Text += String.Format("For key = 2, value = {0}.",
openWith[2]) + "\n";
// The indexer throws an exception when setting a value
// if the key is of the wrong data type.
try
{
openWith[2] = "This does not get added.";
}
catch (ArgumentException)
{
outputBlock.Text += String.Format("A key of the wrong type was specified"
+ " when assigning to the indexer.") + "\n";
}
// Unlike the default Item property on the Dictionary class
// itself, IDictionary.Item does not throw an exception
// if the requested key is not in the dictionary.
outputBlock.Text += String.Format("For key = \"tif\", value = {0}.",
openWith["tif"]) + "\n";
// Contains can be used to test keys before inserting
// them.
if (!openWith.Contains("ht"))
{
openWith.Add("ht", "hypertrm.exe");
outputBlock.Text += String.Format("Value added for key = \"ht\": {0}",
openWith["ht"]) + "\n";
}
// IDictionary.Contains returns false if the wrong data
// type is supplied.
outputBlock.Text += String.Format("openWith.Contains(29.7) returns {0}",
openWith.Contains(29.7)) + "\n";
// When you use foreach to enumerate dictionary elements
// with the IDictionary interface, the elements are retrieved
// as DictionaryEntry objects instead of KeyValuePair objects.
outputBlock.Text += "\n";
foreach (DictionaryEntry de in openWith)
{
outputBlock.Text += String.Format("Key = {0}, Value = {1}",
de.Key, de.Value) + "\n";
}
// To get the values alone, use the Values property.
ICollection icoll = openWith.Values;
// The elements of the collection are strongly typed
// with the type that was specified for dictionary values,
// even though the ICollection interface is not strongly
// typed.
outputBlock.Text += "\n";
foreach (string s in icoll)
{
outputBlock.Text += String.Format("Value = {0}", s) + "\n";
}
// To get the keys alone, use the Keys property.
icoll = openWith.Keys;
// The elements of the collection are strongly typed
// with the type that was specified for dictionary keys,
// even though the ICollection interface is not strongly
// typed.
outputBlock.Text += "\n";
foreach (string s in icoll)
{
outputBlock.Text += String.Format("Key = {0}", s) + "\n";
}
// Use the Remove method to remove a key/value pair. No
// exception is thrown if the wrong data type is supplied.
outputBlock.Text += "\nRemove(\"dib\")" + "\n";
openWith.Remove("dib");
if (!openWith.Contains("dib"))
{
outputBlock.Text += "Key \"dib\" is not found." + "\n";
}
}
}
/* This code example produces the following output:
An exception was caught for IDictionary.Add. Exception message:
The value "42" is not of type "System.String" and cannot be used in this generic collection.
Parameter name: key
An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
The indexer returns null if the key is of the wrong type:
For key = 2, value = .
A key of the wrong type was specified when assigning to the indexer.
For key = "tif", value = .
Value added for key = "ht": hypertrm.exe
openWith.Contains(29.7) returns False
Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe
Value = notepad.exe
Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe
Value = hypertrm.exe
Key = txt
Key = bmp
Key = dib
Key = rtf
Key = doc
Key = ht
Remove("dib")
Key "dib" is not found.
*/
Version Information
Silverlight
Supported in: 5, 4, 3
Silverlight for Windows Phone
Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0
XNA Framework
Supported in: Xbox 360, Windows Phone OS 7.0
Platforms
For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.
See Also