Dictionary<'TKey, 'TValue>.Item Property ('TKey)
Gets or sets the value associated with the specified key.
Assembly: mscorlib (in mscorlib.dll)
abstract Item : key:'TKey -> 'TValue with get, set override Item : key:'TKey -> 'TValue with get, set
The key of the value to get or set.
Property ValueType: TValue
The value associated with the specified key. If the specified key is not found, a get operation throws a KeyNotFoundException, and a set operation creates a new element with the specified key.
This property provides the ability to access a specific element in the collection by using the following C# syntax: myCollection[key] (myCollection(key) in Visual Basic).
You can also use the Dictionary<'TKey, 'TValue>. When you set the property value, if the key is in the Dictionary<'TKey, 'TValue>, the value associated with that key is replaced by the assigned value. If the key is not in the Dictionary<'TKey, 'TValue>, the key and value are added to the dictionary. In contrast, the Add method does not modify existing elements.property to add new elements by setting the value of a key that does not exist in the
A key cannot be null, but a value can be, if the value type TValue is a reference type.
The C# language uses the keyword to define the indexers instead of implementing theproperty. Visual Basic implements as a default property, which provides the same indexing functionality.
Getting or setting the value of this property approaches an O(1) operation.
The following code example uses the KeyNotFoundException is thrown when a requested key is not present, and showing that the value associated with a key can be replaced.property (the indexer in C#) to retrieve values, demonstrating that a
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 example is part of a larger example provided for the Dictionary<'TKey, 'TValue> class. openWith is the name of the Dictionary used in this example.
Available since 8
Available since 2.0
Portable Class Library
Supported in: portable .NET platforms
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Available since 8.1