Duration (Pacific Standard Time):
To (Pacific Standard Time):
Impact:
  • None
User Action:
  • None

Hashtable Class

 

Represents a collection of key/value pairs that are organized based on the hash code of the key.

To browse the .NET Framework source code for this type, see the Reference Source.

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


<SerializableAttribute>
<ComVisibleAttribute(True)>
Public Class Hashtable
	Implements IDictionary, ICollection, IEnumerable, ISerializable,
	IDeserializationCallback, ICloneable
Name Description
System_CAPS_pubmethod Hashtable()

Initializes a new, empty instance of the Hashtable class using the default initial capacity, load factor, hash code provider, and comparer.

System_CAPS_pubmethod Hashtable(IDictionary)

Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the default load factor, hash code provider, and comparer.

System_CAPS_pubmethod Hashtable(IDictionary, IEqualityComparer)

Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to a new Hashtable object. The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the default load factor and the specified IEqualityComparer object.

System_CAPS_pubmethod Hashtable(IDictionary, IHashCodeProvider, IComparer)

Obsolete.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the default load factor, and the specified hash code provider and comparer. This API is obsolete. For an alternative, see Hashtable.

System_CAPS_pubmethod Hashtable(IDictionary, Single)

Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the specified load factor, and the default hash code provider and comparer.

System_CAPS_pubmethod Hashtable(IDictionary, Single, IEqualityComparer)

Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the specified load factor and IEqualityComparer object.

System_CAPS_pubmethod Hashtable(IDictionary, Single, IHashCodeProvider, IComparer)

Obsolete.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the specified load factor, hash code provider, and comparer.

System_CAPS_pubmethod Hashtable(IEqualityComparer)

Initializes a new, empty instance of the Hashtable class using the default initial capacity and load factor, and the specified IEqualityComparer object.

System_CAPS_pubmethod Hashtable(IHashCodeProvider, IComparer)

Obsolete.Initializes a new, empty instance of the Hashtable class using the default initial capacity and load factor, and the specified hash code provider and comparer.

System_CAPS_pubmethod Hashtable(Int32)

Initializes a new, empty instance of the Hashtable class using the specified initial capacity, and the default load factor, hash code provider, and comparer.

System_CAPS_pubmethod Hashtable(Int32, IEqualityComparer)

Initializes a new, empty instance of the Hashtable class using the specified initial capacity and IEqualityComparer, and the default load factor.

System_CAPS_pubmethod Hashtable(Int32, IHashCodeProvider, IComparer)

Obsolete.Initializes a new, empty instance of the Hashtable class using the specified initial capacity, hash code provider, comparer, and the default load factor.

System_CAPS_pubmethod Hashtable(Int32, Single)

Initializes a new, empty instance of the Hashtable class using the specified initial capacity and load factor, and the default hash code provider and comparer.

System_CAPS_pubmethod Hashtable(Int32, Single, IEqualityComparer)

Initializes a new, empty instance of the Hashtable class using the specified initial capacity, load factor, and IEqualityComparer object.

System_CAPS_pubmethod Hashtable(Int32, Single, IHashCodeProvider, IComparer)

Obsolete.Initializes a new, empty instance of the Hashtable class using the specified initial capacity, load factor, hash code provider, and comparer.

System_CAPS_protmethod Hashtable(SerializationInfo, StreamingContext)

Initializes a new, empty instance of the Hashtable class that is serializable using the specified SerializationInfo and StreamingContext objects.

Name Description
System_CAPS_protproperty comparer

Obsolete.Gets or sets the IComparer to use for the Hashtable.

System_CAPS_pubproperty Count

Gets the number of key/value pairs contained in the Hashtable.

System_CAPS_protproperty EqualityComparer

Gets the IEqualityComparer to use for the Hashtable.

System_CAPS_protproperty hcp

Obsolete.Gets or sets the object that can dispense hash codes.

System_CAPS_pubproperty IsFixedSize

Gets a value indicating whether the Hashtable has a fixed size.

System_CAPS_pubproperty IsReadOnly

Gets a value indicating whether the Hashtable is read-only.

System_CAPS_pubproperty IsSynchronized

Gets a value indicating whether access to the Hashtable is synchronized (thread safe).

System_CAPS_pubproperty Item[Object]

Gets or sets the value associated with the specified key.

System_CAPS_pubproperty Keys

Gets an ICollection containing the keys in the Hashtable.

System_CAPS_pubproperty SyncRoot

Gets an object that can be used to synchronize access to the Hashtable.

System_CAPS_pubproperty Values

Gets an ICollection containing the values in the Hashtable.

Name Description
System_CAPS_pubmethod Add(Object, Object)

Adds an element with the specified key and value into the Hashtable.

System_CAPS_pubmethod Clear()

Removes all elements from the Hashtable.

System_CAPS_pubmethod Clone()

Creates a shallow copy of the Hashtable.

System_CAPS_pubmethod Contains(Object)

Determines whether the Hashtable contains a specific key.

System_CAPS_pubmethod ContainsKey(Object)

Determines whether the Hashtable contains a specific key.

System_CAPS_pubmethod ContainsValue(Object)

Determines whether the Hashtable contains a specific value.

System_CAPS_pubmethod CopyTo(Array, Int32)

Copies the Hashtable elements to a one-dimensional Array instance at the specified index.

System_CAPS_pubmethod Equals(Object)

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_protmethod Finalize()

Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)

System_CAPS_pubmethod GetEnumerator()

Returns an IDictionaryEnumerator that iterates through the Hashtable.

System_CAPS_protmethod GetHash(Object)

Returns the hash code for the specified key.

System_CAPS_pubmethod GetHashCode()

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethod GetObjectData(SerializationInfo, StreamingContext)

Implements the ISerializable interface and returns the data needed to serialize the Hashtable.

System_CAPS_pubmethod GetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_protmethod KeyEquals(Object, Object)

Compares a specific Object with a specific key in the Hashtable.

System_CAPS_protmethod MemberwiseClone()

Creates a shallow copy of the current Object.(Inherited from Object.)

System_CAPS_pubmethod OnDeserialization(Object)

Implements the ISerializable interface and raises the deserialization event when the deserialization is complete.

System_CAPS_pubmethod Remove(Object)

Removes the element with the specified key from the Hashtable.

System_CAPS_pubmethod System_CAPS_static Synchronized(Hashtable)

Returns a synchronized (thread-safe) wrapper for the Hashtable.

System_CAPS_pubmethod ToString()

Returns a string that represents the current object.(Inherited from Object.)

Name Description
System_CAPS_pubinterface System_CAPS_privmethod IEnumerable.GetEnumerator()

Returns an enumerator that iterates through a collection.

Name Description
System_CAPS_pubmethod AsParallel()

Overloaded. Enables parallelization of a query.(Defined by ParallelEnumerable.)

System_CAPS_pubmethod AsQueryable()

Overloaded. Converts an IEnumerable to an IQueryable.(Defined by Queryable.)

System_CAPS_pubmethod Cast<TResult>()

Casts the elements of an IEnumerable to the specified type.(Defined by Enumerable.)

System_CAPS_pubmethod OfType<TResult>()

Filters the elements of an IEnumerable based on a specified type.(Defined by Enumerable.)

System_CAPS_note Note

To view the .NET Framework source code for this type, see the Reference Source. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.

Each element is a key/value pair stored in a DictionaryEntry object. A key cannot be null, but a value can be.

The objects used as keys by a Hashtable are required to override the Object.GetHashCode method (or the IHashCodeProvider interface) and the Object.Equals method (or the IComparer interface). The implementation of both methods and interfaces must handle case sensitivity the same way; otherwise, the Hashtable might behave incorrectly. For example, when creating a Hashtable, you must use the CaseInsensitiveHashCodeProvider class (or any case-insensitive IHashCodeProvider implementation) with the CaseInsensitiveComparer class (or any case-insensitive IComparer implementation).

Furthermore, these methods must produce the same results when called with the same parameters while the key exists in the Hashtable. An alternative is to use a Hashtable constructor with an IEqualityComparer parameter. If key equality were simply reference equality, the inherited implementation of Object.GetHashCode and Object.Equals would suffice.

Key objects must be immutable as long as they are used as keys in the Hashtable.

When an element is added to the Hashtable, the element is placed into a bucket based on the hash code of the key. Subsequent lookups of the key use the hash code of the key to search in only one particular bucket, thus substantially reducing the number of key comparisons required to find an element.

The load factor of a Hashtable determines the maximum ratio of elements to buckets. Smaller load factors cause faster average lookup times at the cost of increased memory consumption. The default load factor of 1.0 generally provides the best balance between speed and size. A different load factor can also be specified when the Hashtable is created.

As elements are added to a Hashtable, the actual load factor of the Hashtable increases. When the actual load factor reaches the specified load factor, the number of buckets in the Hashtable is automatically increased to the smallest prime number that is larger than twice the current number of Hashtable buckets.

Each key object in the Hashtable must provide its own hash function, which can be accessed by calling GetHash. However, any object implementing IHashCodeProvider can be passed to a Hashtable constructor, and that hash function is used for all objects in the table.

The capacity of a Hashtable is the number of elements the Hashtable can hold. As elements are added to a Hashtable, the capacity is automatically increased as required through reallocation.

For very large Hashtable objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the enabled attribute of the configuration element to true in the run-time environment.

The foreach statement of the C# language (For Each in Visual Basic) returns an object of the type of the elements in the collection. Since each element of the Hashtable is a key/value pair, the element type is not the type of the key or the type of the value. Instead, the element type is DictionaryEntry. For example:

For Each de As DictionaryEntry In myHashtable
    ' ...
Next de

The foreach statement is a wrapper around the enumerator, which only allows reading from, not writing to, the collection.

Because serializing and deserializing an enumerator for a Hashtable can cause the elements to become reordered, it is not possible to continue enumeration without calling the Reset method.

System_CAPS_note Note

Because keys can be inherited and their behavior changed, their absolute uniqueness cannot be guaranteed by comparisons using the Equals method.

The following example shows how to create, initialize and perform various functions to a Hashtable and how to print out its keys and values.

Imports System
Imports System.Collections

Module Example

    Sub Main()

        ' Create a new hash table.
        '
        Dim openWith As New Hashtable()

        ' Add some elements to the hash table. There are no 
        ' duplicate keys, but some of the values are duplicates.
        openWith.Add("txt", "notepad.exe")
        openWith.Add("bmp", "paint.exe")
        openWith.Add("dib", "paint.exe")
        openWith.Add("rtf", "wordpad.exe")

        ' The Add method throws an exception if the new key is 
        ' already in the hash table.
        Try
            openWith.Add("txt", "winword.exe")
        Catch
            Console.WriteLine("An element with Key = ""txt"" already exists.")
        End Try

        ' The Item property is the default property, so you 
        ' can omit its name when accessing elements. 
        Console.WriteLine("For key = ""rtf"", value = {0}.", _
            openWith("rtf"))

        ' The default Item property can be used to change the value
        ' associated with a key.
        openWith("rtf") = "winword.exe"
        Console.WriteLine("For key = ""rtf"", value = {0}.", _
            openWith("rtf"))

        ' If a key does not exist, setting the default Item property
        ' for that key adds a new key/value pair.
        openWith("doc") = "winword.exe"

        ' ContainsKey can be used to test keys before inserting 
        ' them.
        If Not openWith.ContainsKey("ht") Then
            openWith.Add("ht", "hypertrm.exe")
            Console.WriteLine("Value added for key = ""ht"": {0}", _
                openWith("ht"))
        End If

        ' When you use foreach to enumerate hash table elements,
        ' the elements are retrieved as KeyValuePair objects.
        Console.WriteLine()
        For Each de As DictionaryEntry In openWith
            Console.WriteLine("Key = {0}, Value = {1}", _
                de.Key, de.Value)
        Next de

        ' To get the values alone, use the Values property.
        Dim valueColl As ICollection = openWith.Values

        ' The elements of the ValueCollection are strongly typed
        ' with the type that was specified for hash table values.
        Console.WriteLine()
        For Each s As String In valueColl
            Console.WriteLine("Value = {0}", s)
        Next s

        ' To get the keys alone, use the Keys property.
        Dim keyColl As ICollection = openWith.Keys

        ' The elements of the KeyCollection are strongly typed
        ' with the type that was specified for hash table keys.
        Console.WriteLine()
        For Each s As String In keyColl
            Console.WriteLine("Key = {0}", s)
        Next s

        ' Use the Remove method to remove a key/value pair.
        Console.WriteLine(vbLf + "Remove(""doc"")")
        openWith.Remove("doc")

        If Not openWith.ContainsKey("doc") Then
            Console.WriteLine("Key ""doc"" is not found.")
        End If

    End Sub

End Module

' This code example produces the following output:
'
'An element with Key = "txt" already exists.
'For key = "rtf", value = wordpad.exe.
'For key = "rtf", value = winword.exe.
'Value added for key = "ht": hypertrm.exe
'
'Key = dib, Value = paint.exe
'Key = txt, Value = notepad.exe
'Key = ht, Value = hypertrm.exe
'Key = bmp, Value = paint.exe
'Key = rtf, Value = winword.exe
'Key = doc, Value = winword.exe
'
'Value = paint.exe
'Value = notepad.exe
'Value = hypertrm.exe
'Value = paint.exe
'Value = winword.exe
'Value = winword.exe
'
'Key = dib
'Key = txt
'Key = ht
'Key = bmp
'Key = rtf
'Key = doc
'
'Remove("doc")
'Key "doc" is not found.
Universal Windows Platform
Available since 10
.NET Framework
Available since 1.1

Hashtable is thread safe for use by multiple reader threads and a single writing thread. It is thread safe for multi-thread use when only one of the threads perform write (update) operations, which allows for lock-free reads provided that the writers are serialized to the Hashtable. To support multiple writers all operations on the Hashtable must be done through the wrapper returned by the Synchronized method, provided that there are no threads reading the Hashtable object.

Enumerating through a collection is intrinsically not a thread safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

Return to top