IDictionary<'TKey, 'TValue>.Item Property ('TKey)
Gets or sets the element with the specified key.
Assembly: mscorlib (in mscorlib.dll)
| Exception | Condition |
|---|---|
| ArgumentNullException | key is null. |
| KeyNotFoundException | The property is retrieved and key is not found. |
| NotSupportedException | The property is set and the IDictionary<'TKey, 'TValue> is read-only. |
This property provides the ability to access a specific element in the collection by using the following syntax: myCollection[key] (myCollection(key) in Visual Basic).
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.
The C# language uses the keyword to define the indexers instead of implementing the Item property. Visual Basic implements Item as a default property, which provides the same indexing functionality.
Implementations can vary in whether they allow key to be null.
The following code 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 also 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.
This code is part of a larger example that can be compiled and executed. See System.Collections.Generic.IDictionary<'TKey, 'TValue>.
Available since 8
.NET Framework
Available since 2.0
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1