Export (0) Print
Expand All
12 out of 14 rated this helpful - Rate this topic

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 : IDictionary, ICollection, 
	IEnumerable, ISerializable, IDeserializationCallback, ICloneable

The Hashtable type exposes the following members.

  NameDescription
Public methodSupported by the XNA FrameworkHashtable()Initializes a new, empty instance of the Hashtable class using the default initial capacity, load factor, hash code provider, and comparer.
Public methodSupported by the XNA FrameworkHashtable(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.
Public methodSupported by the XNA FrameworkHashtable(IEqualityComparer)Initializes a new, empty instance of the Hashtable class using the default initial capacity and load factor, and the specified IEqualityComparer object.
Public methodSupported by the XNA FrameworkHashtable(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.
Public methodSupported by the XNA FrameworkHashtable(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.
Public methodSupported by the XNA FrameworkHashtable(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.
Public methodSupported by the XNA FrameworkHashtable(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.
Public methodSupported by the XNA FrameworkHashtable(Int32, IEqualityComparer)Initializes a new, empty instance of the Hashtable class using the specified initial capacity and IEqualityComparer, and the default load factor.
Public methodSupported by the XNA FrameworkHashtable(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.
Protected methodHashtable(SerializationInfo, StreamingContext)Initializes a new, empty instance of the Hashtable class that is serializable using the specified SerializationInfo and StreamingContext objects.
Public methodSupported by the XNA FrameworkHashtable(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.
Public methodSupported by the XNA FrameworkHashtable(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.
Public methodSupported by the XNA FrameworkHashtable(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.
Public methodSupported by the XNA FrameworkHashtable(Int32, Single, IEqualityComparer)Initializes a new, empty instance of the Hashtable class using the specified initial capacity, load factor, and IEqualityComparer object.
Public methodHashtable(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.
Public methodHashtable(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.
Top
  NameDescription
Protected propertySupported by the XNA Frameworkcomparer Obsolete. Gets or sets the IComparer to use for the Hashtable.
Public propertySupported by the XNA FrameworkCountGets the number of key/value pairs contained in the Hashtable.
Protected propertySupported by the XNA FrameworkEqualityComparerGets the IEqualityComparer to use for the Hashtable.
Protected propertySupported by the XNA Frameworkhcp Obsolete. Gets or sets the object that can dispense hash codes.
Public propertySupported by the XNA FrameworkIsFixedSizeGets a value indicating whether the Hashtable has a fixed size.
Public propertySupported by the XNA FrameworkIsReadOnlyGets a value indicating whether the Hashtable is read-only.
Public propertySupported by the XNA FrameworkIsSynchronizedGets a value indicating whether access to the Hashtable is synchronized (thread safe).
Public propertySupported by the XNA FrameworkItemGets or sets the value associated with the specified key.
Public propertySupported by the XNA FrameworkKeysGets an ICollection containing the keys in the Hashtable.
Public propertySupported by the XNA FrameworkSyncRootGets an object that can be used to synchronize access to the Hashtable.
Public propertySupported by the XNA FrameworkValuesGets an ICollection containing the values in the Hashtable.
Top
  NameDescription
Public methodSupported by the XNA FrameworkAddAdds an element with the specified key and value into the Hashtable.
Public methodSupported by the XNA FrameworkClearRemoves all elements from the Hashtable.
Public methodSupported by the XNA FrameworkCloneCreates a shallow copy of the Hashtable.
Public methodSupported by the XNA FrameworkContainsDetermines whether the Hashtable contains a specific key.
Public methodSupported by the XNA FrameworkContainsKeyDetermines whether the Hashtable contains a specific key.
Public methodSupported by the XNA FrameworkContainsValueDetermines whether the Hashtable contains a specific value.
Public methodSupported by the XNA FrameworkCopyToCopies the Hashtable elements to a one-dimensional Array instance at the specified index.
Public methodSupported by the XNA FrameworkEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by the XNA FrameworkGetEnumeratorReturns an IDictionaryEnumerator that iterates through the Hashtable.
Protected methodSupported by the XNA FrameworkGetHashReturns the hash code for the specified key.
Public methodSupported by the XNA FrameworkGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetObjectDataImplements the ISerializable interface and returns the data needed to serialize the Hashtable.
Public methodSupported by the XNA FrameworkGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkKeyEqualsCompares a specific Object with a specific key in the Hashtable.
Protected methodSupported by the XNA FrameworkMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodOnDeserializationImplements the ISerializable interface and raises the deserialization event when the deserialization is complete.
Public methodSupported by the XNA FrameworkRemoveRemoves the element with the specified key from the Hashtable.
Public methodStatic memberSupported by the XNA FrameworkSynchronizedReturns a synchronized (thread-safe) wrapper for the Hashtable.
Public methodSupported by the XNA FrameworkToStringReturns a string that represents the current object. (Inherited from Object.)
Top
  NameDescription
Public Extension MethodAsParallelEnables parallelization of a query. (Defined by ParallelEnumerable.)
Public Extension MethodAsQueryableConverts an IEnumerable to an IQueryable. (Defined by Queryable.)
Public Extension MethodSupported by the XNA FrameworkCast<TResult>Casts the elements of an IEnumerable to the specified type. (Defined by Enumerable.)
Public Extension MethodSupported by the XNA FrameworkOfType<TResult>Filters the elements of an IEnumerable based on a specified type. (Defined by Enumerable.)
Top
  NameDescription
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIEnumerable.GetEnumeratorReturns an enumerator that iterates through a collection.
Top
NoteNote

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 gcAllowVeryLargeObjects configuration element to true in the run-time environment.

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/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:

foreach(DictionaryEntry de in myHashtable)
{
    // ...
}

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.

NoteNote

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.

using System;
using System.Collections;

class Example
{
    public static void Main()
    {
        // Create a new hash table. 
        //
        Hashtable openWith = 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.");
        }

        // 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 (!openWith.ContainsKey("ht"))
        {
            openWith.Add("ht", "hypertrm.exe");
            Console.WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]);
        }

        // When you use foreach to enumerate hash table elements, 
        // the elements are retrieved as KeyValuePair objects.
        Console.WriteLine();
        foreach( DictionaryEntry de in openWith )
        {
            Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
        }

        // To get the values alone, use the Values property.
        ICollection valueColl = openWith.Values;

        // The elements of the ValueCollection are strongly typed 
        // with the type that was specified for hash table values.
        Console.WriteLine();
        foreach( string s in valueColl )
        {
            Console.WriteLine("Value = {0}", s);
        }

        // To get the keys alone, use the Keys property.
        ICollection keyColl = openWith.Keys;

        // The elements of the KeyCollection are strongly typed 
        // with the type that was specified for hash table keys.
        Console.WriteLine();
        foreach( string s in keyColl )
        {
            Console.WriteLine("Key = {0}", s);
        }

        // Use the Remove method to remove a key/value pair.
        Console.WriteLine("\nRemove(\"doc\")");
        openWith.Remove("doc");

        if (!openWith.ContainsKey("doc"))
        {
            Console.WriteLine("Key \"doc\" is not found.");
        }
    }
}

/* 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.
 */

.NET Framework

Supported in: 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

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.

Show:
© 2014 Microsoft. All rights reserved.