System.Collections.Hashtable Class

Assembly: Mscorlib.dll
Namespace: System.Collections
Summary
Represents a collection of key-and-value pairs that are organized based on the hash code of the key.
C# Syntax:
[Serializable]
public class Hashtable : IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable
Thread Safety
A Hashtable can safely support one writer and multiple readers concurrently. To support multiple writers, all operations must be done through the wrapper returned by the Hashtable.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.

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 Hashtable.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 foreach statement of the C# language 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: foreach (DictionaryEntry myEntry in myHashtable) {...}

Example
The following example shows how to create and initialize a Hashtable and how to print out its keys and values.
 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
 */ 

    
See also:
System.Collections Namespace | IDictionary | IHashCodeProvider | Object.GetHashCode | Object.Equals | DictionaryEntry

System.Collections.Hashtable Member List:

Public Constructors
ctor #1 Overloaded:
.ctor()

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
Creates an empty Hashtable with the default initial capacity and using the default load factor, the default hash code provider and the default comparer.
ctor #2 Overloaded:
.ctor(IDictionary d)

Copies the elements from the specified dictionary to a new Hashtable with the same initial capacity as the number of elements copied and using the default load factor, the default hash code provider and the default comparer.
ctor #3 Overloaded:
.ctor(int capacity)

Creates an empty Hashtable with the specified initial capacity and using the default load factor, the default hash code provider and the default comparer.
ctor #4 Overloaded:
.ctor(IDictionary d, float loadFactor)

Copies the elements from the specified dictionary to a new Hashtable with the same initial capacity as the number of elements copied and using the specified load factor, the default hash code provider and the default comparer.
ctor #5 Overloaded:
.ctor(IHashCodeProvider hcp, IComparer comparer)

Creates an empty Hashtable with the default initial capacity and using the default load factor, the specified hash code provider and the specified comparer.
ctor #6 Overloaded:
.ctor(int capacity, float loadFactor)

Creates an empty Hashtable with the specified initial capacity and using the specified load factor, the default hash code provider and the default comparer.
ctor #8 Overloaded:
.ctor(IDictionary d, IHashCodeProvider hcp, IComparer comparer)

Copies the elements from the specified dictionary to a new Hashtable with the same initial capacity as the number of elements copied and using the default load factor, the specified hash code provider and the specified comparer.
ctor #9 Overloaded:
.ctor(int capacity, IHashCodeProvider hcp, IComparer comparer)

Creates an empty Hashtable with the specified initial capacity and using the default load factor, the specified hash code provider and the specified comparer.
ctor #10 Overloaded:
.ctor(IDictionary d, float loadFactor, IHashCodeProvider hcp, IComparer comparer)

Copies the elements from the specified dictionary to a new Hashtable with the same initial capacity as the number of elements copied and using the specified load factor, the specified hash code provider and the specified comparer.
ctor #11 Overloaded:
.ctor(int capacity, float loadFactor, IHashCodeProvider hcp, IComparer comparer)

Creates an empty Hashtable with the specified initial capacity and using the specified load factor, the specified hash code provider and the specified comparer.
Public Properties
Count Read-only

Gets the number of key-and-value pairs contained in the Hashtable.
IsFixedSize Read-only

Gets a value indicating whether the Hashtable has a fixed size.
IsReadOnly Read-only

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

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

Gets or sets the value associated with the specified key.
Keys Read-only

Gets an ICollection containing the keys in the Hashtable.
SyncRoot Read-only

Gets an object that can be used to synchronize access to the Hashtable.
Values Read-only

Gets an ICollection containing the values in the Hashtable.
Public Methods
Add Adds an element with the specified key and value into the Hashtable.
Clear Removes all elements from the Hashtable.
Clone Creates a shallow copy of the Hashtable.
Contains Determines whether the Hashtable contains a specific key.
ContainsKey Determines whether the Hashtable contains a specific key.
ContainsValue Determines whether the Hashtable contains a specific value.
CopyTo Copies the Hashtable elements to a one-dimensional Array instance at the specified index.
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
GetEnumerator Returns an IDictionaryEnumerator that can iterate through the Hashtable.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetObjectData Implements the ISerializable interface and returns the data needed to serialize the Hashtable.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
OnDeserialization Implements the ISerializable interface and raises the deserialization event when the deserialization is complete.
Remove Removes the element with the specified key from the Hashtable.
Synchronized Returns a synchronized (thread-safe) wrapper for the Hashtable.
ToString
(inherited from System.Object)
See base class member description: System.Object.ToString

Derived from System.Object, the primary base class for all objects.
Protected Constructors
ctor #7 Overloaded:
.ctor(SerializationInfo info, StreamingContext context)

Creates an empty Hashtable that is serializable with the specified SerializationInfo and StreamingContext.
Protected Properties
comparer Read-write

Gets or sets the comparer to use for the Hashtable.
hcp Read-write

Gets or sets the object that can dispense hash codes.
Protected Methods
Finalize
(inherited from System.Object)
See base class member description: System.Object.Finalize

Derived from System.Object, the primary base class for all objects.
GetHash Returns the hash code for the specified key.
KeyEquals Compares a specific Object with a specific key in the Hashtable.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.
Explicit Interface Implementations 
IEnumerable.GetEnumerator Returns an IEnumerator that can iterate through the Hashtable.

Hierarchy:


System.Collections.Hashtable Member Details

Overloaded ctor #1
Summary
Creates an empty Hashtable with the default initial capacity and using the default load factor, the default hash code provider and the default comparer.

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
C# Syntax:
public Hashtable();
Remarks
A hashtable's capacity is used to calculate the optimal number of hashtable buckets based on the load factor. The default initial capacity is zero. Capacity is automatically increased as required.

The load factor is the maximum ratio of elements to buckets. A smaller load factor means faster lookup at the cost of increased memory consumption. The default load factor is 1.0, which is the best balance between speed and size.

When the actual load factor reaches the load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

The hash code provider dispenses hash codes for keys in the Hashtable. The default hash code provider is the key's implementation of Object.GetHashCode.

The comparer determines whether two keys are equal. Every key in a Hashtable must be unique. The default comparer is the key's implementation of Object.Equals.

See also:
Object.GetHashCode | Object.Equals

Return to top


Overloaded ctor #2
Summary
Copies the elements from the specified dictionary to a new Hashtable with the same initial capacity as the number of elements copied and using the default load factor, the default hash code provider and the default comparer.
C# Syntax:
public Hashtable(
   IDictionary d
);
Parameters:

d

The IDictionary to copy to a new Hashtable.

Exceptions
Exception Type Condition
ArgumentNullException d is null.
Remarks
The initial capacity is set to the number of elements in the source dictionary. Capacity is automatically increased as required based on the load factor.

The load factor is the maximum ratio of elements to buckets. A smaller load factor means faster lookup at the cost of increased memory consumption. The default load factor is 1.0, which is the best balance between speed and size.

When the actual load factor reaches the load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

The hash code provider dispenses hash codes for keys in the Hashtable. The default hash code provider is the key's implementation of Object.GetHashCode.

The comparer determines whether two keys are equal. Every key in a Hashtable must be unique. The default comparer is the key's implementation of Object.Equals.

The elements of the new Hashtable are sorted in the same order in which the enumerator iterates through the IDictionary.

See also:
IDictionary | Object.GetHashCode | Object.Equals

Return to top


Overloaded ctor #3
Summary
Creates an empty Hashtable with the specified initial capacity and using the default load factor, the default hash code provider and the default comparer.
C# Syntax:
public Hashtable(
   int capacity
);
Parameters:

capacity

The approximate number of elements that the Hashtable can initially contain.

Exceptions
Exception Type Condition
ArgumentOutOfRangeException capacity is less than zero.
Remarks
Specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Hashtable. Capacity is automatically increased as required based on the load factor.

The load factor is the maximum ratio of elements to buckets. A smaller load factor means faster lookup at the cost of increased memory consumption. The default load factor is 1.0, which is the best balance between speed and size.

When the actual load factor reaches the load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

The hash code provider dispenses hash codes for keys in the Hashtable. The default hash code provider is the key's implementation of Object.GetHashCode.

The comparer determines whether two keys are equal. Every key in a Hashtable must be unique. The default comparer is the key's implementation of Object.Equals.

See also:
Object.GetHashCode | Object.Equals

Return to top


Overloaded ctor #4
Summary
Copies the elements from the specified dictionary to a new Hashtable with the same initial capacity as the number of elements copied and using the specified load factor, the default hash code provider and the default comparer.
C# Syntax:
public Hashtable(
   IDictionary d,
   float loadFactor
);
Parameters:

d

The IDictionary to copy to a new Hashtable.

loadFactor

A number in the range from 0.1 through 1.0 indicating the maximum ratio of elements to buckets.

Exceptions
Exception Type Condition
ArgumentNullException d is null.
ArgumentOutOfRangeException loadFactor is less than 0.1.

-or-

loadFactor is greater than 1.0.

Remarks
The initial capacity is set to the number of elements in the source dictionary. Capacity is automatically increased as required based on the load factor.

The load factor is the maximum ratio of elements to buckets. A smaller load factor means faster lookup at the cost of increased memory consumption. A load factor of 1.0 is the best balance between speed and size.

When the actual load factor reaches the load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

The hash code provider dispenses hash codes for keys in the Hashtable. The default hash code provider is the key's implementation of Object.GetHashCode.

The comparer determines whether two keys are equal. Every key in a Hashtable must be unique. The default comparer is the key's implementation of Object.Equals.

The elements of the new Hashtable are sorted in the same order in which the enumerator iterates through the IDictionary.

See also:
IDictionary | Object.GetHashCode | Object.Equals

Return to top


Overloaded ctor #5
Summary
Creates an empty Hashtable with the default initial capacity and using the default load factor, the specified hash code provider and the specified comparer.
C# Syntax:
public Hashtable(
   IHashCodeProvider hcp,
   IComparer comparer
);
Parameters:

hcp

The IHashCodeProvider that supplies the hash codes for all keys in the Hashtable.

-or-

null to use the default hash code provider, which is each key's implementation of Object.GetHashCode.

The IHashCodeProvider that supplies the hash codes for all keys in the Hashtable.

-or-

null to use the default hash code provider, which is each key's implementation of Object.GetHashCode.

comparer

The IComparer to use to determine whether two keys are equal.

-or-

null to use the default comparer, which is each key's implementation of Object.Equals.

The IComparer to use to determine whether two keys are equal.

-or-

null to use the default comparer, which is each key's implementation of Object.Equals.

Remarks
A hashtable's capacity is used to calculate the optimal number of hashtable buckets based on the load factor. The default initial capacity is zero. Capacity is automatically increased as required.

The load factor is the maximum ratio of elements to buckets. A smaller load factor means faster lookup at the cost of increased memory consumption. The default load factor is 1.0, which is the best balance between speed and size.

When the actual load factor reaches the load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

The hash code provider dispenses hash codes for keys in the Hashtable. The default hash code provider is the key's implementation of Object.GetHashCode.

The comparer determines whether two keys are equal. Every key in a Hashtable must be unique. The default comparer is the key's implementation of Object.Equals.

The custom hash code provider and the custom comparer enable such scenarios as doing lookups with case-insensitive strings.

See also:
IHashCodeProvider | IComparer | Object.GetHashCode | Object.Equals

Return to top


Overloaded ctor #6
Summary
Creates an empty Hashtable with the specified initial capacity and using the specified load factor, the default hash code provider and the default comparer.
C# Syntax:
public Hashtable(
   int capacity,
   float loadFactor
);
Parameters:

capacity

The approximate number of elements that the Hashtable can initially contain.

loadFactor

A number in the range from 0.1 through 1.0 indicating the maximum ratio of elements to buckets.

Exceptions
Exception Type Condition
ArgumentOutOfRangeException capacity is less than zero.

-or-

loadFactor is less than 0.1.

-or-

loadFactor is greater than 1.0.

Remarks
Specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Hashtable. Capacity is automatically increased as required based on the load factor.

The load factor is the maximum ratio of elements to buckets. A smaller load factor means faster lookup at the cost of increased memory consumption. A load factor of 1.0 is the best balance between speed and size.

When the actual load factor reaches the load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

The hash code provider dispenses hash codes for keys in the Hashtable. The default hash code provider is the key's implementation of Object.GetHashCode.

The comparer determines whether two keys are equal. Every key in a Hashtable must be unique. The default comparer is the key's implementation of Object.Equals.

See also:
Object.GetHashCode | Object.Equals

Return to top


Overloaded ctor #7
Summary
Creates an empty Hashtable that is serializable with the specified SerializationInfo and StreamingContext.
C# Syntax:
protected Hashtable(
   SerializationInfo info,
   StreamingContext context
);
Parameters:

info

A SerializationInfo object containing the information required to serialize the Hashtable.

context

A StreamingContext object containing the source and destination of the serialized stream associated with the Hashtable.

Exceptions
Exception Type Condition
ArgumentNullException info is null.
Remarks
A hashtable's capacity is used to calculate the optimal number of hashtable buckets based on the load factor. The default initial capacity is zero. Capacity is automatically increased as required.

The load factor is the maximum ratio of elements to buckets. A smaller load factor means faster lookup at the cost of increased memory consumption. The default load factor is 1.0, which is the best balance between speed and size.

When the actual load factor reaches the load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

The hash code provider dispenses hash codes for keys in the Hashtable. The default hash code provider is the key's implementation of Object.GetHashCode.

The comparer determines whether two keys are equal. Every key in a Hashtable must be unique. The default comparer is the key's implementation of Object.Equals.

See also:
ISerializable | SerializationInfo | StreamingContext | Hashtable.OnDeserialization | Object.GetHashCode | Object.Equals

Return to top


Overloaded ctor #8
Summary
Copies the elements from the specified dictionary to a new Hashtable with the same initial capacity as the number of elements copied and using the default load factor, the specified hash code provider and the specified comparer.
C# Syntax:
public Hashtable(
   IDictionary d,
   IHashCodeProvider hcp,
   IComparer comparer
);
Parameters:

d

The IDictionary to copy to a new Hashtable.

hcp

The IHashCodeProvider that supplies the hash codes for all keys in the Hashtable.

-or-

null to use the default hash code provider, which is each key's implementation of Object.GetHashCode.

The IHashCodeProvider that supplies the hash codes for all keys in the Hashtable.

-or-

null to use the default hash code provider, which is each key's implementation of Object.GetHashCode.

comparer

The IComparer to use to determine whether two keys are equal.

-or-

null to use the default comparer, which is each key's implementation of Object.Equals.

The IComparer to use to determine whether two keys are equal.

-or-

null to use the default comparer, which is each key's implementation of Object.Equals.

Exceptions
Exception Type Condition
ArgumentNullException d is null.
Remarks
The initial capacity is set to the number of elements in the source dictionary. Capacity is automatically increased as required based on the load factor.

The load factor is the maximum ratio of elements to buckets. A smaller load factor means faster lookup at the cost of increased memory consumption. The default load factor is 1.0, which is the best balance between speed and size.

When the actual load factor reaches the load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

The hash code provider dispenses hash codes for keys in the Hashtable. The default hash code provider is the key's implementation of Object.GetHashCode.

The comparer determines whether two keys are equal. Every key in a Hashtable must be unique. The default comparer is the key's implementation of Object.Equals.

The custom hash code provider and the custom comparer enables scenarios such as doing lookups with case-insensitive strings.

The elements of the new Hashtable are sorted in the same order in which the enumerator iterates through the IDictionary.

See also:
IDictionary | IHashCodeProvider | IComparer | Object.GetHashCode | Object.Equals

Return to top


Overloaded ctor #9
Summary
Creates an empty Hashtable with the specified initial capacity and using the default load factor, the specified hash code provider and the specified comparer.
C# Syntax:
public Hashtable(
   int capacity,
   IHashCodeProvider hcp,
   IComparer comparer
);
Parameters:

capacity

The approximate number of elements that the Hashtable can initially contain.

hcp

The IHashCodeProvider that supplies the hash codes for all keys in the Hashtable.

-or-

null to use the default hash code provider, which is each key's implementation of Object.GetHashCode.

The IHashCodeProvider that supplies the hash codes for all keys in the Hashtable.

-or-

null to use the default hash code provider, which is each key's implementation of Object.GetHashCode.

comparer

The IComparer to use to determine whether two keys are equal.

-or-

null to use the default comparer, which is each key's implementation of Object.Equals.

The IComparer to use to determine whether two keys are equal.

-or-

null to use the default comparer, which is each key's implementation of Object.Equals.

Remarks
Specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Hashtable. Capacity is automatically increased as required based on the load factor.

The load factor is the maximum ratio of elements to buckets. A smaller load factor means faster lookup at the cost of increased memory consumption. The default load factor is 1.0, which is the best balance between speed and size.

When the actual load factor reaches the load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

The hash code provider dispenses hash codes for keys in the Hashtable. The default hash code provider is the key's implementation of Object.GetHashCode.

The comparer determines whether two keys are equal. Every key in a Hashtable must be unique. The default comparer is the key's implementation of Object.Equals.

The custom hash code provider and the custom comparer enable such scenarios as doing lookups with case-insensitive strings.

See also:
IHashCodeProvider | IComparer | Object.GetHashCode | Object.Equals

Return to top


Overloaded ctor #10
Summary
Copies the elements from the specified dictionary to a new Hashtable with the same initial capacity as the number of elements copied and using the specified load factor, the specified hash code provider and the specified comparer.
C# Syntax:
public Hashtable(
   IDictionary d,
   float loadFactor,
   IHashCodeProvider hcp,
   IComparer comparer
);
Parameters:

d

The IDictionary to copy to a new Hashtable.

loadFactor

A number in the range from 0.1 through 1.0 indicating the maximum ratio of elements to buckets.

hcp

The IHashCodeProvider that supplies the hash codes for all keys in the Hashtable.

-or-

null to use the default hash code provider, which is each key's implementation of Object.GetHashCode.

The IHashCodeProvider that supplies the hash codes for all keys in the Hashtable.

-or-

null to use the default hash code provider, which is each key's implementation of Object.GetHashCode.

comparer

The IComparer to use to determine whether two keys are equal.

-or-

null to use the default comparer, which is each key's implementation of Object.Equals.

The IComparer to use to determine whether two keys are equal.

-or-

null to use the default comparer, which is each key's implementation of Object.Equals.

Exceptions
Exception Type Condition
ArgumentNullException d is null.
ArgumentOutOfRangeException loadFactor is less than 0.1.

-or-

loadFactor is greater than 1.0.

Remarks
The initial capacity is set to the number of elements in the source dictionary. Capacity is automatically increased as required based on the load factor.

The load factor is the maximum ratio of elements to buckets. A smaller load factor means faster lookup at the cost of increased memory consumption. A load factor of 1.0 is the best balance between speed and size.

When the actual load factor reaches the load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

The hash code provider dispenses hash codes for keys in the Hashtable. The default hash code provider is the key's implementation of Object.GetHashCode.

The comparer determines whether two keys are equal. Every key in a Hashtable must be unique. The default comparer is the key's implementation of Object.Equals.

The custom hash code provider and the custom comparer enable such scenarios as doing lookups with case-insensitive strings.

The elements of the new Hashtable are sorted in the same order in which the enumerator iterates through the IDictionary.

Return to top


Overloaded ctor #11
Summary
Creates an empty Hashtable with the specified initial capacity and using the specified load factor, the specified hash code provider and the specified comparer.
C# Syntax:
public Hashtable(
   int capacity,
   float loadFactor,
   IHashCodeProvider hcp,
   IComparer comparer
);
Parameters:

capacity

The approximate number of elements that the Hashtable can initially contain.

loadFactor

A number in the range from 0.1 through 1.0 indicating the maximum ratio of elements to buckets.

hcp

The IHashCodeProvider that supplies the hash codes for all keys in the Hashtable.

-or-

null to use the default hash code provider, which is each key's implementation of Object.GetHashCode.

The IHashCodeProvider that supplies the hash codes for all keys in the Hashtable.

-or-

null to use the default hash code provider, which is each key's implementation of Object.GetHashCode.

comparer

The IComparer to use to determine whether two keys are equal.

-or-

null to use the default comparer, which is each key's implementation of Object.Equals.

The IComparer to use to determine whether two keys are equal.

-or-

null to use the default comparer, which is each key's implementation of Object.Equals.

Exceptions
Exception Type Condition
ArgumentOutOfRangeException capacity is less than zero.

-or-

loadFactor is less than 0.1.

-or-

loadFactor is greater than 1.0.

Remarks
Specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Hashtable. Capacity is automatically increased as required based on the load factor.

The load factor is the maximum ratio of elements to buckets. A smaller load factor means faster lookup at the cost of increased memory consumption. A load factor of 1.0 is the best balance between speed and size.

When the actual load factor reaches the load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

The hash code provider dispenses hash codes for keys in the Hashtable. The default hash code provider is the key's implementation of Object.GetHashCode.

The comparer determines whether two keys are equal. Every key in a Hashtable must be unique. The default comparer is the key's implementation of Object.Equals.

The custom hash code provider and the custom comparer enable such scenarios as doing lookups with case-insensitive strings.

See also:
IHashCodeProvider | IComparer | Object.GetHashCode | Object.Equals

Return to top


Property: comparer (read-write)
Summary
Gets or sets the comparer to use for the Hashtable.
C# Syntax:
protected IComparer comparer {get; set;}
See also:
IComparer

Return to top


Property: Count (read-only)
Summary
Gets the number of key-and-value pairs contained in the Hashtable.
C# Syntax:
public virtual int Count {get;}
Implements:
ICollection.Count

Return to top


Property: hcp (read-write)
Summary
Gets or sets the object that can dispense hash codes.
C# Syntax:
protected IHashCodeProvider hcp {get; set;}
See also:
IHashCodeProvider

Return to top


Property: IsFixedSize (read-only)
Summary
Gets a value indicating whether the Hashtable has a fixed size.
C# Syntax:
public virtual bool IsFixedSize {get;}
Implements:
IDictionary.IsFixedSize
Remarks
A collection with a fixed size does not allow the addition or removal of elements after the collection is created, but it allows the modification of existing elements.

Return to top


Property: IsReadOnly (read-only)
Summary
Gets a value indicating whether the Hashtable is read-only.
C# Syntax:
public virtual bool IsReadOnly {get;}
Implements:
IDictionary.IsReadOnly
Remarks
A collection that is read-only does not allow the addition, removal, or modification of elements after the collection is created.

Return to top


Property: IsSynchronized (read-only)
Summary
Gets a value indicating whether access to the Hashtable is synchronized (thread-safe).
C# Syntax:
public virtual bool IsSynchronized {get;}
Implements:
ICollection.IsSynchronized
Remarks
A Hashtable can safely support one writer and multiple readers concurrently. To support multiple writers, all operations must be done through the wrapper returned by the Hashtable.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.

The following code example shows how to lock the collection using the Hashtable.SyncRoot during the entire enumeration:

              Hashtable myCollection = new Hashtable();
               lock( myCollection.SyncRoot ) {
               foreach ( Object item in myCollection ) {
               // Insert your code here.
               }
              }
            
Example
The following example shows how to synchronize a Hashtable, determine if a Hashtable is synchronized and use a synchronized Hashtable.
 using System;
 using System.Collections;
 public class SamplesHashtable  {
 
    public static void Main()  {
 
       // Creates and initializes a new Hashtable.
       Hashtable myHT = new Hashtable();
       myHT.Add( 0, "zero" );
       myHT.Add( 1, "one" );
       myHT.Add( 2, "two" );
       myHT.Add( 3, "three" );
       myHT.Add( 4, "four" );
 
       // Creates a synchronized wrapper around the Hashtable.
       Hashtable mySyncdHT = Hashtable.Synchronized( myHT );
 
       // Displays the sychronization status of both Hashtables.
       Console.WriteLine( "myHT is {0}.", myHT.IsSynchronized ? "synchronized" : "not synchronized" );
       Console.WriteLine( "mySyncdHT is {0}.", mySyncdHT.IsSynchronized ? "synchronized" : "not synchronized" );
    }
 }
 /* 
 This code produces the following output.
 
 myHT is not synchronized.
 mySyncdHT is synchronized.
 */ 

    
See also:
Hashtable.Synchronized | Hashtable.SyncRoot

Return to top


Property: Item (read-write)
Summary
Gets or sets the value associated with the specified key.
C# Syntax:
public virtual object this[object key] {get; set;}
Parameters:

key

The key whose value to get or set.

Exceptions
Exception Type Condition
ArgumentNullException key is null.
NotSupportedException The property is set and the Hashtable is read-only.

-or-

The property is set, key does not exist in the collection, and the Hashtable has a fixed size.

Implements:
IDictionary.Item
Remarks
This property provides the ability to access a specific element in the collection by using the following syntax: myCollection[key] .

When setting this property, if the specified key already exists in the Hashtable, the value is replaced; otherwise, a new element is created. In contrast, the Hashtable.Add method does not modify existing elements.

See also:
Hashtable.Add

Return to top


Property: Keys (read-only)
Summary
Gets an ICollection containing the keys in the Hashtable.
C# Syntax:
public virtual ICollection Keys {get;}
Implements:
IDictionary.Keys
Remarks
The order of the keys in the ICollection is unspecified, but it is the same order as the associated values in the ICollection returned by the Hashtable.Values method.

The returned ICollection is a reference to the original Hashtable, not a static copy. Therefore, changes to the Hashtable continue to be reflected in the ICollection.

See also:
ICollection | Hashtable.Values

Return to top


Property: SyncRoot (read-only)
Summary
Gets an object that can be used to synchronize access to the Hashtable.
C# Syntax:
public virtual object SyncRoot {get;}
Implements:
ICollection.SyncRoot
Remarks
To create a synchronized version of the Hashtable, use the Hashtable.Synchronized method. However, derived classes can provide their own synchronized version of the Hashtable using the Hashtable.SyncRoot property. The synchronizing code must perform operations on the Hashtable.SyncRoot of the Hashtable, not directly on the Hashtable. This ensures proper operation of collections that are derived from other objects. Specifically, it maintains proper synchronization with other threads that might be simultaneously modifying the Hashtable object.

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.

The following code example shows how to lock the collection using the Hashtable.SyncRoot during the entire enumeration:

              Hashtable myCollection = new Hashtable();
               lock( myCollection.SyncRoot ) {
               foreach ( Object item in myCollection ) {
               // Insert your code here.
               }
              }
            
See also:
Hashtable.IsSynchronized | Hashtable.Synchronized

Return to top


Property: Values (read-only)
Summary
Gets an ICollection containing the values in the Hashtable.
C# Syntax:
public virtual ICollection Values {get;}
Implements:
IDictionary.Values
Remarks
The order of the values in the ICollection is unspecified, but it is the same order as the associated keys in the ICollection returned by the Hashtable.Keys method.

The returned ICollection is a reference to the original Hashtable, not a static copy. Therefore, changes to the Hashtable continue to be reflected in the ICollection.

See also:
ICollection | Hashtable.Keys

Return to top


Method: Add(
   object key,
   object value
)
Summary
Adds an element with the specified key and value into the Hashtable.
C# Syntax:
public virtual void Add(
   object key,
   object value
);
Parameters:

key

The key of the element to add.

value

The value of the element to add.

Exceptions
Exception Type Condition
ArgumentNullException key is null.
ArgumentException An element with the same key already exists in the Hashtable.
NotSupportedException The Hashtable is read-only.

-or-

The Hashtable has a fixed size.

Implements:
IDictionary.Add
Remarks
An object that has no correlation between its state and its hash code value should typically not be used as the key. For example, String objects are better than StringBuilder objects for use as keys.

The Hashtable.Item property can also be used to add new elements by setting the value of a key that does not exist in the Hashtable. For example: myCollection["myNonexistentKey"] = myValue . However, if the specified key already exists in the Hashtable, setting the Hashtable.Item property overwrites the old value. In contrast, the Hashtable.Add method does not modify existing elements.

Example
The following example shows how to add elements to the Hashtable.
 using System;
 using System.Collections;
 public class SamplesHashtable  {
 
    public static void Main()  {
 
       // Creates and initializes a new Hashtable.
       Hashtable myHT = new Hashtable();
       myHT.Add( "one", "The" );
       myHT.Add( "two", "quick" );
       myHT.Add( "three", "brown" );
       myHT.Add( "four", "fox" );
 
       // Displays the Hashtable.
       Console.WriteLine( "The Hashtable contains the following:" );
       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.
 
 The Hashtable contains the following:
     -KEY-    -VALUE-
     three:    brown
     four:    fox
     two:    quick
     one:    The
 */ 

    
See also:
Hashtable.Remove | Hashtable.Item | IDictionary.Add

Return to top


Method: Clear()
Summary
Removes all elements from the Hashtable.
C# Syntax:
public virtual void Clear();
Exceptions
Exception Type Condition
NotSupportedException The Hashtable is read-only.
Implements:
IDictionary.Clear
Remarks
Hashtable.Count is set to zero. The capacity remains unchanged.
Example
The following example shows how to clear the values of the Hashtable.
 using System;
 using System.Collections;
 public class SamplesHashtable  {
 
    public static void Main()  {
 
       // Creates and initializes a new Hashtable.
       Hashtable myHT = new Hashtable();
       myHT.Add( "one", "The" );
       myHT.Add( "two", "quick" );
       myHT.Add( "three", "brown" );
       myHT.Add( "four", "fox" );
       myHT.Add( "five", "jumped" );
 
       // Displays the count and values of the Hashtable.
       Console.WriteLine( "Initially," );
       Console.WriteLine( "   Count    : {0}", myHT.Count );
       Console.WriteLine( "   Values:" );
       PrintKeysAndValues( myHT );
 
       // Clears the Hashtable.
       myHT.Clear();
 
       // Displays the count and values of the Hashtable.
       Console.WriteLine( "After Clear," );
       Console.WriteLine( "   Count    : {0}", myHT.Count );
       Console.WriteLine( "   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.
 
 Initially,
    Count    : 5
    Values:
     -KEY-    -VALUE-
     five:    jumped
     three:    brown
     four:    fox
     two:    quick
     one:    The
 
 After Clear,
    Count    : 0
    Values:
     -KEY-    -VALUE-
 */ 

    
See also:
IDictionary.Clear

Return to top


Method: Clone()
Summary
Creates a shallow copy of the Hashtable.
C# Syntax:
public virtual object Clone();
Return Value:
A shallow copy of the Hashtable.
Implements:
ICloneable.Clone
Remarks
A shallow copy of a collection copies only the elements of the collection, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new collection point to the same objects that the references in the original collection point to.

In contrast, a deep copy of a collection copies the elements and everything directly or indirectly referenced by the elements.

The Hashtable clone has the same count, the same capacity, the same IHashCodeProvider implementation, and the same IComparer implementation as the original Hashtable.

See also:
Hashtable.CopyTo

Return to top


Method: Contains(
   object key
)
Summary
Determines whether the Hashtable contains a specific key.
C# Syntax:
public virtual bool Contains(
   object key
);
Parameters:

key

The key to locate in the Hashtable.

Return Value:
true if the Hashtable contains an element with the specified key; otherwise, false.
Exceptions
Exception Type Condition
ArgumentNullException key is null.
Implements:
IDictionary.Contains
Remarks
This implementation is close to O(1) in most cases.

Hashtable.Contains implements IDictionary.Contains. It behaves exactly as Hashtable.ContainsKey.

Example
The following example shows how to determine whether the Hashtable contains a specific element.
 using System;
 using System.Collections;
 public class SamplesHashtable  {
 
    public static void Main()  {
 
       // Creates and initializes a new Hashtable.
       Hashtable myHT = new Hashtable();
       myHT.Add( 0, "zero" );
       myHT.Add( 1, "one" );
       myHT.Add( 2, "two" );
       myHT.Add( 3, "three" );
       myHT.Add( 4, "four" );
 
       // Displays the values of the Hashtable.
       Console.WriteLine( "The Hashtable contains the following values:" );
       PrintIndexAndKeysAndValues( myHT );
 
       // Searches for a specific key.
       int myKey = 2;
       Console.WriteLine( "The key \"{0}\" is {1}.", myKey, myHT.ContainsKey( myKey ) ? "in the Hashtable" : "NOT in the Hashtable" );
       myKey = 6;
       Console.WriteLine( "The key \"{0}\" is {1}.", myKey, myHT.ContainsKey( myKey ) ? "in the Hashtable" : "NOT in the Hashtable" );
 
       // Searches for a specific value.
       String myValue = "three";
       Console.WriteLine( "The value \"{0}\" is {1}.", myValue, myHT.ContainsValue( myValue ) ? "in the Hashtable" : "NOT in the Hashtable" );
       myValue = "nine";
       Console.WriteLine( "The value \"{0}\" is {1}.", myValue, myHT.ContainsValue( myValue ) ? "in the Hashtable" : "NOT in the Hashtable" );
    }
 
 
    public static void PrintIndexAndKeysAndValues( Hashtable myList )  {
       IDictionaryEnumerator myEnumerator = myList.GetEnumerator();
       int i = 0;
       Console.WriteLine( "\t-INDEX-\t-KEY-\t-VALUE-" );
       while ( myEnumerator.MoveNext() )
          Console.WriteLine( "\t[{0}]:\t{1}\t{2}", i++, myEnumerator.Key, myEnumerator.Value );
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 The Hashtable contains the following values:
     -INDEX-    -KEY-    -VALUE-
     [0]:    4    four
     [1]:    3    three
     [2]:    2    two
     [3]:    1    one
     [4]:    0    zero
 
 The key "2" is in the Hashtable.
 The key "6" is NOT in the Hashtable.
 The value "three" is in the Hashtable.
 The value "nine" is NOT in the Hashtable.
 */ 

    
See also:
Hashtable.ContainsKey | IDictionary

Return to top


Method: ContainsKey(
   object key
)
Summary
Determines whether the Hashtable contains a specific key.
C# Syntax:
public virtual bool ContainsKey(
   object key
);
Parameters:

key

The key to locate in the Hashtable.

Return Value:
true if the Hashtable contains an element with the specified key; otherwise, false.
Exceptions
Exception Type Condition
ArgumentNullException key is null.
Remarks
This implementation is close to O(1) in most cases.

This method behaves exactly as Hashtable.Contains.

Example
The following example shows how to determine whether the Hashtable contains a specific element.
 using System;
 using System.Collections;
 public class SamplesHashtable  {
 
    public static void Main()  {
 
       // Creates and initializes a new Hashtable.
       Hashtable myHT = new Hashtable();
       myHT.Add( 0, "zero" );
       myHT.Add( 1, "one" );
       myHT.Add( 2, "two" );
       myHT.Add( 3, "three" );
       myHT.Add( 4, "four" );
 
       // Displays the values of the Hashtable.
       Console.WriteLine( "The Hashtable contains the following values:" );
       PrintIndexAndKeysAndValues( myHT );
 
       // Searches for a specific key.
       int myKey = 2;
       Console.WriteLine( "The key \"{0}\" is {1}.", myKey, myHT.ContainsKey( myKey ) ? "in the Hashtable" : "NOT in the Hashtable" );
       myKey = 6;
       Console.WriteLine( "The key \"{0}\" is {1}.", myKey, myHT.ContainsKey( myKey ) ? "in the Hashtable" : "NOT in the Hashtable" );
 
       // Searches for a specific value.
       String myValue = "three";
       Console.WriteLine( "The value \"{0}\" is {1}.", myValue, myHT.ContainsValue( myValue ) ? "in the Hashtable" : "NOT in the Hashtable" );
       myValue = "nine";
       Console.WriteLine( "The value \"{0}\" is {1}.", myValue, myHT.ContainsValue( myValue ) ? "in the Hashtable" : "NOT in the Hashtable" );
    }
 
 
    public static void PrintIndexAndKeysAndValues( Hashtable myList )  {
       IDictionaryEnumerator myEnumerator = myList.GetEnumerator();
       int i = 0;
       Console.WriteLine( "\t-INDEX-\t-KEY-\t-VALUE-" );
       while ( myEnumerator.MoveNext() )
          Console.WriteLine( "\t[{0}]:\t{1}\t{2}", i++, myEnumerator.Key, myEnumerator.Value );
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 The Hashtable contains the following values:
     -INDEX-    -KEY-    -VALUE-
     [0]:    4    four
     [1]:    3    three
     [2]:    2    two
     [3]:    1    one
     [4]:    0    zero
 
 The key "2" is in the Hashtable.
 The key "6" is NOT in the Hashtable.
 The value "three" is in the Hashtable.
 The value "nine" is NOT in the Hashtable.
 */ 

    
See also:
Hashtable.Contains | Hashtable.ContainsValue

Return to top


Method: ContainsValue(
   object value
)
Summary
Determines whether the Hashtable contains a specific value.
C# Syntax:
public virtual bool ContainsValue(
   object value
);
Parameters:

value

The value to locate in the Hashtable.

Return Value:
true if the Hashtable contains an element with the specified value; otherwise, false.
Remarks
This method performs a linear search; therefore, the average execution time is proportional to Hashtable.Count. That is, this method is an O(n) operation, where n is Hashtable.Count.

The values of the elements of the Hashtable are compared to the specified value using the Object.Equals method.

Example
The following example shows how to determine whether the Hashtable contains a specific element.
 using System;
 using System.Collections;
 public class SamplesHashtable  {
 
    public static void Main()  {
 
       // Creates and initializes a new Hashtable.
       Hashtable myHT = new Hashtable();
       myHT.Add( 0, "zero" );
       myHT.Add( 1, "one" );
       myHT.Add( 2, "two" );
       myHT.Add( 3, "three" );
       myHT.Add( 4, "four" );
 
       // Displays the values of the Hashtable.
       Console.WriteLine( "The Hashtable contains the following values:" );
       PrintIndexAndKeysAndValues( myHT );
 
       // Searches for a specific key.
       int myKey = 2;
       Console.WriteLine( "The key \"{0}\" is {1}.", myKey, myHT.ContainsKey( myKey ) ? "in the Hashtable" : "NOT in the Hashtable" );
       myKey = 6;
       Console.WriteLine( "The key \"{0}\" is {1}.", myKey, myHT.ContainsKey( myKey ) ? "in the Hashtable" : "NOT in the Hashtable" );
 
       // Searches for a specific value.
       String myValue = "three";
       Console.WriteLine( "The value \"{0}\" is {1}.", myValue, myHT.ContainsValue( myValue ) ? "in the Hashtable" : "NOT in the Hashtable" );
       myValue = "nine";
       Console.WriteLine( "The value \"{0}\" is {1}.", myValue, myHT.ContainsValue( myValue ) ? "in the Hashtable" : "NOT in the Hashtable" );
    }
 
 
    public static void PrintIndexAndKeysAndValues( Hashtable myList )  {
       IDictionaryEnumerator myEnumerator = myList.GetEnumerator();
       int i = 0;
       Console.WriteLine( "\t-INDEX-\t-KEY-\t-VALUE-" );
       while ( myEnumerator.MoveNext() )
          Console.WriteLine( "\t[{0}]:\t{1}\t{2}", i++, myEnumerator.Key, myEnumerator.Value );
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 The Hashtable contains the following values:
     -INDEX-    -KEY-    -VALUE-
     [0]:    4    four
     [1]:    3    three
     [2]:    2    two
     [3]:    1    one
     [4]:    0    zero
 
 The key "2" is in the Hashtable.
 The key "6" is NOT in the Hashtable.
 The value "three" is in the Hashtable.
 The value "nine" is NOT in the Hashtable.
 */ 

    
See also:
Hashtable.ContainsKey | Object.Equals

Return to top


Method: CopyTo(
   Array array,
   int arrayIndex
)
Summary
Copies the Hashtable elements to a one-dimensional Array instance at the specified index.
C# Syntax:
public virtual void CopyTo(
   Array array,
   int arrayIndex
);
Parameters:

array

The one-dimensional Array that is the destination of the DictionaryEntry objects copied from Hashtable. The Array must have zero-based indexing.

arrayIndex

The zero-based index in array at which copying begins.

Exceptions
Exception Type Condition
ArgumentNullException array is null.
ArgumentOutOfRangeException arrayIndex is less than zero.
ArgumentException array is multidimensional.

-or-

arrayIndex is equal to or greater than the length of array.

-or-

The number of elements in the source Hashtable is greater than the available space from arrayIndex to the end of the destination array.

InvalidCastException The type of the source Hashtable cannot be cast automatically to the type of the destination array.
Implements:
ICollection.CopyTo
Remarks
The elements are copied to the Array in the same order in which the enumerator iterates through the Hashtable.

To copy only the keys in the Hashtable, use Hashtable.Keys.CopyTo .

To copy only the values in the Hashtable, use Hashtable.Values.CopyTo .

Example
The following example shows how to copy the list of keys or the list of values in a Hashtable into a one-dimensional Array.
 using System;
 using System.Collections;
 public class SamplesHashtable  {
 
    public static void Main()  {
 
       // Creates and initializes the source Hashtable.
       Hashtable mySourceHT = new Hashtable();
       mySourceHT.Add( "A", "alpha" );
       mySourceHT.Add( "B", "beta" );
 
       // Creates and initializes the one-dimensional target Array.
       Array myTargetArray=Array.CreateInstance( typeof(String), 15 );
       myTargetArray.SetValue( "The", 0 );
       myTargetArray.SetValue( "quick", 1 );
       myTargetArray.SetValue( "brown", 2 );
       myTargetArray.SetValue( "fox", 3 );
       myTargetArray.SetValue( "jumped", 4 );
       myTargetArray.SetValue( "over", 5 );
       myTargetArray.SetValue( "the", 6 );
       myTargetArray.SetValue( "lazy", 7 );
       myTargetArray.SetValue( "dog", 8 );
 
       // Displays the values of the target Array.
       Console.WriteLine( "The target Array contains the following before:" );
       PrintValues( myTargetArray, ' ' );
 
       // Copies the keys in the source Hashtable to the target Hashtable, starting at index 6.
       Console.WriteLine( "After copying the keys, starting at index 6:" );
       mySourceHT.Keys.CopyTo( myTargetArray, 6 );
 
       // Displays the values of the target Array.
       PrintValues( myTargetArray, ' ' );
 
       // Copies the values in the source Hashtable to the target Hashtable, starting at index 6.
       Console.WriteLine( "After copying the values, starting at index 6:" );
       mySourceHT.Values.CopyTo( myTargetArray, 6 );
 
       // Displays the values of the target Array.
       PrintValues( myTargetArray, ' ' );
    }
 
    public static void PrintValues( Array myArr, char mySeparator )  {
       System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
       int i = 0;
       int cols = myArr.GetLength( myArr.Rank - 1 );
       while ( myEnumerator.MoveNext() )  {
          if ( i < cols )  {
             i++;
          } else  {
             Console.WriteLine();
             i = 1;
          }
          Console.Write( "{0}{1}", mySeparator, myEnumerator.Current );
       }
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 The target Array contains the following before:
  The quick brown fox jumped over the lazy dog
 After copying the keys, starting at index 6:
  The quick brown fox jumped over A B dog
 After copying the values, starting at index 6:
  The quick brown fox jumped over alpha beta dog
 */ 

    
See also:
Array | DictionaryEntry | Hashtable.GetEnumerator

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~Hashtable();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetEnumerator()
Summary
Returns an IDictionaryEnumerator that can iterate through the Hashtable.
C# Syntax:
public virtual IDictionaryEnumerator GetEnumerator();
Return Value:
An IDictionaryEnumerator for the Hashtable.
Implements:
IDictionary.GetEnumerator
Remarks
Enumerators only allow reading the data in the collection. Enumerators cannot be used to modify the underlying collection.

Initially, the enumerator is positioned before the first element in the collection. IEnumerator.Reset also brings the enumerator back to this position. At this position, calling IEnumerator.Current throws an exception. Therefore, you must call IEnumerator.MoveNext to advance the enumerator to the first element of the collection before reading the value of IEnumerator.Current.

IEnumerator.Current returns the same object until either IEnumerator.MoveNext or IEnumerator.Reset is called. IEnumerator.MoveNext sets IEnumerator.Current to the next element.

After the end of the collection is passed, the enumerator is positioned after the last element in the collection, and calling IEnumerator.MoveNext returns false. If the last call to IEnumerator.MoveNext returned false, calling IEnumerator.Current throws an exception. To set IEnumerator.Current to the first element of the collection again, you can call IEnumerator.Reset followed by IEnumerator.MoveNext.

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying or deleting elements, the enumerator is irrecoverably invalidated and the next call to IEnumerator.MoveNext or IEnumerator.Reset throws an InvalidOperationException. If the collection is modified between IEnumerator.MoveNext and IEnumerator.Current, IEnumerator.Current will return the element that it is set to, even if the enumerator is already invalidated.

The enumerator does not have exclusive access to the collection; therefore, 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.

See also:
IDictionaryEnumerator | IEnumerator

Return to top


Method: GetHash(
   object key
)
Summary
Returns the hash code for the specified key.
C# Syntax:
protected virtual int GetHash(
   object key
);
Parameters:

key

The Object for which a hash code is to be returned.

Return Value:
The hash code for key.
Exceptions
Exception Type Condition
ArgumentNullException key is null.
Remarks
If the hashtable was created with a specific IHashCodeProvider implementation, this method uses that hash code provider; otherwise, it uses the Object.GetHashCode implementation of key.
See also:
Object.GetHashCode | Object | IHashCodeProvider

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetObjectData(
   SerializationInfo info,
   StreamingContext context
)
Summary
Implements the ISerializable interface and returns the data needed to serialize the Hashtable.
C# Syntax:
public virtual void GetObjectData(
   SerializationInfo info,
   StreamingContext context
);
Parameters:

info

A SerializationInfo object containing the information required to serialize the Hashtable.

context

A StreamingContext object containing the source and destination of the serialized stream associated with the Hashtable.

Exceptions
Exception Type Condition
ArgumentNullException info is null.
Implements:
ISerializable.GetObjectData
See also:
ISerializable | SerializationInfo | StreamingContext | Hashtable.OnDeserialization

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: KeyEquals(
   object item,
   object key
)
Summary
Compares a specific Object with a specific key in the Hashtable.
C# Syntax:
protected virtual bool KeyEquals(
   object item,
   object key
);
Parameters:

item

The Object to compare with key.

key

The key in the Hashtable to compare with item.

Return Value:
true if item and key are equal; otherwise, false.
Exceptions
Exception Type Condition
ArgumentNullException item is null.

-or-

key is null.

Remarks
If the hashtable was created with a specific IComparer implementation, this method uses that comparer; that is, IComparer.Compare (item, key). Otherwise, it uses item.Equals(key) .
See also:
Object | IComparer.Compare | Object.Equals

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: OnDeserialization(
   object sender
)
Summary
Implements the ISerializable interface and raises the deserialization event when the deserialization is complete.
C# Syntax:
public virtual void OnDeserialization(
   object sender
);
Parameters:

sender

The source of the deserialization event.

Exceptions
Exception Type Condition
SerializationException The SerializationInfo object associated with the current Hashtable is invalid.
Implements:
IDeserializationCallback.OnDeserialization
See also:
ISerializable | Hashtable.GetObjectData

Return to top


Method: Remove(
   object key
)
Summary
Removes the element with the specified key from the Hashtable.
C# Syntax:
public virtual void Remove(
   object key
);
Parameters:

key

The key of the element to remove.

Exceptions
Exception Type Condition
ArgumentNullException key is null.
NotSupportedException The Hashtable is read-only.

-or-

The Hashtable has a fixed size.

Implements:
IDictionary.Remove
Remarks
If the Hashtable does not contain an element with the specified key, the Hashtable remains unchanged. No exception is thrown.
Example
The following example shows how to remove elements from the Hashtable.
 using System;
 using System.Collections;
 public class SamplesHashtable  {
 
    public static void Main()  {
 
       // Creates and initializes a new Hashtable.
       Hashtable myHT = new Hashtable();
       myHT.Add( "1a", "The" );
       myHT.Add( "1b", "quick" );
       myHT.Add( "1c", "brown" );
       myHT.Add( "2a", "fox" );
       myHT.Add( "2b", "jumped" );
       myHT.Add( "2c", "over" );
       myHT.Add( "3a", "the" );
       myHT.Add( "3b", "lazy" );
       myHT.Add( "3c", "dog" );
 
       // Displays the Hashtable.
       Console.WriteLine( "The Hashtable initially contains the following:" );
       PrintKeysAndValues( myHT );
 
       // Removes the element with the key "3b".
       myHT.Remove( "3b" );
 
       // Displays the current state of the Hashtable.
       Console.WriteLine( "After removing \"lazy\":" );
       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.
 
 The Hashtable initially contains the following:
     -KEY-    -VALUE-
     3a:    the
     3c:    dog
     3b:    lazy
     1c:    brown
     1b:    quick
     1a:    The
     2a:    fox
     2b:    jumped
     2c:    over
 
 After removing "lazy":
     -KEY-    -VALUE-
     3a:    the
     3c:    dog
     1c:    brown
     1b:    quick
     1a:    The
     2a:    fox
     2b:    jumped
     2c:    over
 */

    
See also:
Hashtable.Add | IDictionary.Remove

Return to top


Method: Synchronized(
   Hashtable table
)
Summary
Returns a synchronized (thread-safe) wrapper for the Hashtable.
C# Syntax:
public static Hashtable Synchronized(
   Hashtable table
);
Parameters:

table

The Hashtable to synchronize.

Return Value:
A synchronized (thread-safe) wrapper for the Hashtable.
Exceptions
Exception Type Condition
ArgumentNullException table is null.
Remarks
A Hashtable can safely support one writer and multiple readers concurrently. To support multiple writers, all operations must be done through this wrapper only.

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.

The following code example shows how to lock the collection using the Hashtable.SyncRoot during the entire enumeration:

              Hashtable myCollection = new Hashtable();
               lock( myCollection.SyncRoot ) {
               foreach ( Object item in myCollection ) {
               // Insert your code here.
               }
              }
            
Example
The following example shows how to synchronize a Hashtable, determine if a Hashtable is synchronized and use a synchronized Hashtable.
 using System;
 using System.Collections;
 public class SamplesHashtable  {
 
    public static void Main()  {
 
       // Creates and initializes a new Hashtable.
       Hashtable myHT = new Hashtable();
       myHT.Add( 0, "zero" );
       myHT.Add( 1, "one" );
       myHT.Add( 2, "two" );
       myHT.Add( 3, "three" );
       myHT.Add( 4, "four" );
 
       // Creates a synchronized wrapper around the Hashtable.
       Hashtable mySyncdHT = Hashtable.Synchronized( myHT );
 
       // Displays the sychronization status of both Hashtables.
       Console.WriteLine( "myHT is {0}.", myHT.IsSynchronized ? "synchronized" : "not synchronized" );
       Console.WriteLine( "mySyncdHT is {0}.", mySyncdHT.IsSynchronized ? "synchronized" : "not synchronized" );
    }
 }
 /* 
 This code produces the following output.
 
 myHT is not synchronized.
 mySyncdHT is synchronized.
 */ 

    
See also:
Hashtable.IsSynchronized | Hashtable.SyncRoot

Return to top


Method: IEnumerable.GetEnumerator()
Summary
Returns an IEnumerator that can iterate through the Hashtable.
C# Syntax:
IEnumerator IEnumerable.GetEnumerator();
Return Value:
An IEnumerator for the Hashtable.
Implements:
IEnumerable.GetEnumerator
Remarks
Enumerators only allow reading the data in the collection. Enumerators cannot be used to modify the underlying collection.

Initially, the enumerator is positioned before the first element in the collection. IEnumerator.Reset also brings the enumerator back to this position. At this position, calling IEnumerator.Current throws an exception. Therefore, you must call IEnumerator.MoveNext to advance the enumerator to the first element of the collection before reading the value of IEnumerator.Current.

IEnumerator.Current returns the same object until either IEnumerator.MoveNext or IEnumerator.Reset is called. IEnumerator.MoveNext sets IEnumerator.Current to the next element.

After the end of the collection is passed, the enumerator is positioned after the last element in the collection, and calling IEnumerator.MoveNext returns false. If the last call to IEnumerator.MoveNext returned false, calling IEnumerator.Current throws an exception. To set IEnumerator.Current to the first element of the collection again, you can call IEnumerator.Reset followed by IEnumerator.MoveNext.

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying or deleting elements, the enumerator is irrecoverably invalidated and the next call to IEnumerator.MoveNext or IEnumerator.Reset throws an InvalidOperationException. If the collection is modified between IEnumerator.MoveNext and IEnumerator.Current, IEnumerator.Current will return the element that it is set to, even if the enumerator is already invalidated.

The enumerator does not have exclusive access to the collection; therefore, 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.

See also:
IDictionaryEnumerator | IEnumerator

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.