TryGetValue Method

SortedDictionary(Of TKey, TValue).TryGetValue Method

[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]

Gets the value associated with the specified key.

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

'Declaration
Public Function TryGetValue ( _
	key As TKey, _
	<OutAttribute> ByRef value As TValue _
) As Boolean

Parameters

key
Type: TKey
The key of the value to get.
value
Type: TValue %
When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter.

Return Value

Type: System.Boolean
true if the SortedDictionary(Of TKey, TValue) contains an element with the specified key; otherwise, false.

Implements

IDictionary(Of TKey, TValue).TryGetValue(TKey, TValue)

ExceptionCondition
ArgumentNullException

key is Nothing.

This method combines the functionality of the ContainsKey method and the Item property.

If the key is not found, then the value parameter gets the appropriate default value for the value type TValue; for example, 0 (zero) for integer types, false for Boolean types, and Nothing for reference types.

This method is an O(log n) operation.

The example shows how to use the TryGetValue method as a more efficient way to retrieve values in a program that frequently tries keys that are not in the dictionary. For contrast, the example also shows how the Item property (the indexer in C#) throws exceptions when attempting to retrieve nonexistent keys.

This code example is part of a larger example provided for the SortedDictionary(Of TKey, TValue) class.

Windows Phone OS

Supported in: 8.1, 8.0

Show:
© 2017 Microsoft