Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Hashtable Class

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

For a list of all members of this type, see Hashtable Members.

System.Object
   System.Collections.Hashtable
      System.Data.PropertyCollection

[Visual Basic]
<Serializable>
Public Class Hashtable
   Implements IDictionary, ICollection, IEnumerable, ISerializable, _
   _
   IDeserializationCallback, ICloneable
[C#]
[Serializable]
public class Hashtable : IDictionary, ICollection, IEnumerable,
   ISerializable, IDeserializationCallback, ICloneable
[C++]
[Serializable]
public __gc class Hashtable : public IDictionary, ICollection,
   IEnumerable, ISerializable, IDeserializationCallback, ICloneable
[JScript]
public
   Serializable
class Hashtable implements IDictionary, ICollection,
   IEnumerable, ISerializable, IDeserializationCallback, ICloneable

Thread Safety

To support one or more writers, all operations on the Hashtable must be done through the wrapper returned by the Synchronized method.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could 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.

Remarks

Each element is a key-and-value pair stored in a DictionaryEntry object. A key cannot be a null reference (Nothing in Visual Basic), but a value can be.

The objects used as keys in a Hashtable must implement or inherit the Object.GetHashCode and Object.Equals methods. If key equality were simply reference equality, the inherited implementation of these methods would suffice. Furthermore, these methods must produce the same results when called with the same parameters while the key exists in the Hashtable. 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 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.

[Visual Basic, C#] The foreach statement of the C# language (for each in Visual Basic) requires the type of each element in the collection. Since each element of the Hashtable is a key-and-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:

[C#] 
foreach (DictionaryEntry myDE in myHashtable) {...}
[Visual Basic] 
Dim myDE As DictionaryEntry
For Each myDE In myHashtable
   ...
Next myDE

[Visual Basic, C#] The foreach statement is a wrapper around the enumerator, which only allows reading from, not writing to, the collection.

Example

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

[Visual Basic] 
Imports System
Imports System.Collections
Imports Microsoft.VisualBasic

Public Class SamplesHashtable    
    
    Public Shared Sub Main()
        
        ' Creates and initializes a new Hashtable.
        Dim myHT As New Hashtable()
        myHT.Add("First", "Hello")
        myHT.Add("Second", "World")
        myHT.Add("Third", "!")
        
        ' Displays the properties and values of the Hashtable.
        Console.WriteLine("myHT")
        Console.WriteLine("  Count:    {0}", myHT.Count)
        Console.WriteLine("  Keys and Values:")
        PrintKeysAndValues(myHT)
    End Sub
    
    Public Shared Sub PrintKeysAndValues(myList As Hashtable)
        Dim myEnumerator As IDictionaryEnumerator = myList.GetEnumerator()
        Console.WriteLine(ControlChars.Tab + "-KEY-" + ControlChars.Tab _
           + "-VALUE-")
        While myEnumerator.MoveNext()
            Console.WriteLine(ControlChars.Tab + "{0}:" + ControlChars.Tab _
               + "{1}", myEnumerator.Key, myEnumerator.Value)
        End While
        Console.WriteLine()
    End Sub
End Class

' This code produces the following output.
' 
' myHT
'   Count:    3
'   Keys and Values:
'     -KEY-    -VALUE-
'     Third:    !
'     Second:    World
'     First:    Hello 

[C#] 
using System;
using System.Collections;
public class SamplesHashtable  {

   public static void Main()  {

      // Creates and initializes a new Hashtable.
      Hashtable myHT = new Hashtable();
      myHT.Add("First", "Hello");
      myHT.Add("Second", "World");
      myHT.Add("Third", "!");

      // Displays the properties and values of the Hashtable.
      Console.WriteLine( "myHT" );
      Console.WriteLine( "  Count:    {0}", myHT.Count );
      Console.WriteLine( "  Keys and Values:" );
      PrintKeysAndValues( myHT );
   }


   public static void PrintKeysAndValues( Hashtable myList )  {
      IDictionaryEnumerator myEnumerator = myList.GetEnumerator();
      Console.WriteLine( "\t-KEY-\t-VALUE-" );
      while ( myEnumerator.MoveNext() )
         Console.WriteLine("\t{0}:\t{1}", myEnumerator.Key, myEnumerator.Value);
      Console.WriteLine();
   }
}
/* 
This code produces the following output.

myHT
  Count:    3
  Keys and Values:
    -KEY-    -VALUE-
    Third:    !
    Second:    World
    First:    Hello
*/ 

[C++] 
#using <mscorlib.dll>
#using <system.dll>

using namespace System;
using namespace System::Collections;

public __gc class SamplesHashtable  {

public:
    static void PrintKeysAndValues(Hashtable __gc *myList ) {
        IDictionaryEnumerator __gc *myEnumerator = myList->GetEnumerator();
        Console::WriteLine(S"\t-KEY-\t-VALUE-");
        while (myEnumerator->MoveNext())
            Console::WriteLine(S"\t{0}:\t{1}", myEnumerator->Key, myEnumerator->Value);
        Console::WriteLine();
    };
};

int main()  {

    // Creates and initializes a new Hashtable.
    Hashtable __gc *myHT = new Hashtable();
    myHT->Add(S"First", S"Hello");
    myHT->Add(S"Second", S"World");
    myHT->Add(S"Third", S"!");

    // Displays the properties and values of the Hashtable.
    Console::WriteLine(S"myHT");
    Console::WriteLine(S"  Count:    {0}", __box(myHT->Count));
    Console::WriteLine(S"  Keys and Values:");
    SamplesHashtable::PrintKeysAndValues(myHT);
}
/* 
This code produces the following output.

myHT
Count:    3
Keys and Values:
-KEY-    -VALUE-
Third:    !
Second:    World
First:    Hello
*/ 

[JScript] 
import System
import System.Collections

// Creates and initializes a new Hashtable.
var myHT : Hashtable = new Hashtable()
myHT.Add("First", "Hello")
myHT.Add("Second", "World")
myHT.Add("Third", "!")

// Displays the properties and values of the Hashtable.
Console.WriteLine("myHT")
Console.WriteLine("  Count:    {0}", myHT.Count)
Console.WriteLine("  Keys and Values:")
PrintKeysAndValues(myHT)
    
function PrintKeysAndValues(myList : Hashtable){
    var myEnumerator : IDictionaryEnumerator = myList.GetEnumerator()
    Console.WriteLine("\t-KEY-\t-VALUE-")
    while(myEnumerator.MoveNext())
        Console.WriteLine("\t{0}:\t{1}", myEnumerator.Key, myEnumerator.Value)
    Console.WriteLine()
}

// This code produces the following output.
// 
// myHT
//   Count:    3
//   Keys and Values:
//     -KEY-    -VALUE-
//     Third:    !
//     Second:   World
//     First:    Hello 

Requirements

Namespace: System.Collections

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework

Assembly: Mscorlib (in Mscorlib.dll)

See Also

Hashtable Members | System.Collections Namespace | IDictionary | IHashCodeProvider | Object.GetHashCode | Object.Equals | DictionaryEntry

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft