Export (0) Print
Expand All

SortedDictionary.Item Property

Gets or sets the value associated with the specified key.

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

public:
virtual property TValue default [TKey] {
	TValue get (TKey key) sealed;
	void set (TKey key, TValue value) sealed;
}
/** @property */
public final TValue get_Item (TKey key)

/** @property */
public final void set_Item (TKey key, TValue value)

Not applicable.

Parameters

key

The key of the value to get or set.

Property Value

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.

Exception typeCondition

ArgumentNullException

key is a null reference (Nothing in Visual Basic).

KeyNotFoundException

The property is retrieved and key does not exist in the collection.

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 Item property to add new elements by setting the value of a key that does not exist in the SortedDictionary; for example, myCollection["myNonexistentKey"] = myValue. However, if the specified key already exists in the SortedDictionary, setting the Item property overwrites the old value. In contrast, the Add method does not modify existing elements.

A key cannot be a null reference (Nothing in Visual Basic), but a value can be, if the value type TValue is a reference type.

The C# language uses the this 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.

Getting the value of this property is an O(log n) operation; setting the property is also an O(log n) operation.

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 example is part of a larger example provided for the SortedDictionary class.

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

Windows 98, Windows Server 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0

Community Additions

ADD
Show:
© 2014 Microsoft