Name

Hashtable.Item Property

Class

System.Collections.Hashtable

Syntax

hashtablevariable.Item(key)
hashtablevariable

Use: Required

Type: Hashtable object

A reference to a Hashtable object

key

Use: Required

Data Type: Object

The key whose value is to be retrieved

Return Value

An Object representing the value associated with key

Description

Returns an Object that is the value associated with a particular key/value pair.

Rules at a Glance

  • Item is the default property of the Hashtable object, and since it is parameterized, we can write:

    hashtablevariable(key)
  • Item is a read/write property. In other words, you can use the Item property to retrieve the value belonging to a particular key, as well as to modify the value belonging to a particular key.

  • If key does not exist in the hash table when you attempt to retrieve a value, the Item property returns Nothing.

  • If key does not exist in the hash table when you attempt to modify a value, the key and its associated value are added to the hash table, as a sort of implicit add. For example, if the key "AK" does not exist in a hash table, the code fragment:

    hshStates.Item("AK") = "Alaska"

    adds the key "AK" and its associated value, "Alaska".

Programming Tips and Gotchas

  • To guard against inadvertently adding a member to the hash table when you intend to modify an existing value, call the ContainsKey method beforehand.

  • You can also retrieve individual members of the Hashtable object by iterating it using the For Each...Next statement. Each iteration of the ...

Get VB .NET Language in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.