[Serializable] |
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 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) {...}
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 */
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. |
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. |
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. |
ctor #7 | Overloaded:.ctor(SerializationInfo info, StreamingContext context) Creates an empty Hashtable that is serializable with the specified SerializationInfo and StreamingContext. |
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. |
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. |
IEnumerable.GetEnumerator | Returns an IEnumerator that can iterate through the Hashtable. |
Hierarchy:
public Hashtable(); |
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.
public Hashtable( |
d
Exception Type | Condition |
---|---|
ArgumentNullException | d is null. |
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.
public Hashtable( |
capacity
Exception Type | Condition |
---|---|
ArgumentOutOfRangeException | capacity is less than zero. |
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.
public Hashtable( |
d
loadFactor
Exception Type | Condition |
---|---|
ArgumentNullException | d is null. |
ArgumentOutOfRangeException | loadFactor is less than 0.1. -or- loadFactor is greater than 1.0. |
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.
public Hashtable( |
hcp
-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
-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.
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.
capacity
loadFactor
Exception Type | Condition |
---|---|
ArgumentOutOfRangeException | capacity is less than zero. -or- loadFactor is less than 0.1. -or- loadFactor is greater than 1.0. |
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.
protected Hashtable( |
info
context
Exception Type | Condition |
---|---|
ArgumentNullException | info is null. |
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.
public Hashtable( |
d
hcp
-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
-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.
Exception Type | Condition |
---|---|
ArgumentNullException | d is null. |
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.
public Hashtable( |
capacity
hcp
-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
-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.
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.
public Hashtable( |
d
loadFactor
hcp
-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
-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.
Exception Type | Condition |
---|---|
ArgumentNullException | d is null. |
ArgumentOutOfRangeException | loadFactor is less than 0.1. -or- loadFactor is greater than 1.0. |
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.
public Hashtable( |
capacity
loadFactor
hcp
-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
-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.
Exception Type | Condition |
---|---|
ArgumentOutOfRangeException | capacity is less than zero. -or- loadFactor is less than 0.1. -or- loadFactor is greater than 1.0. |
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.
protected IComparer comparer {get; set;}
|
public virtual int Count {get;}
|
protected IHashCodeProvider hcp {get; set;}
|
public virtual bool IsFixedSize {get;}
|
public virtual bool IsReadOnly {get;}
|
public virtual bool IsSynchronized {get;}
|
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. } }
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. */
public virtual object this[object key] {get; set;}
|
key
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. |
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.
public virtual ICollection Keys {get;}
|
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.
public virtual object SyncRoot {get;}
|
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. } }
public virtual ICollection Values {get;}
|
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.
key
value
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. |
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.
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 */
public virtual void Clear(); |
Exception Type | Condition |
---|---|
NotSupportedException | The Hashtable is read-only. |
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- */
public virtual object Clone(); |
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.
key
Exception Type | Condition |
---|---|
ArgumentNullException | key is null. |
Hashtable.Contains implements IDictionary.Contains. It behaves exactly as Hashtable.ContainsKey.
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. */
key
Exception Type | Condition |
---|---|
ArgumentNullException | key is null. |
This method behaves exactly as Hashtable.Contains.
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. */
value
The values of the elements of the Hashtable are compared to the specified value using the Object.Equals method.
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. */
array
arrayIndex
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. |
To copy only the keys in the Hashtable, use
Hashtable.Keys.CopyTo
.
To copy only the values in the Hashtable, use
Hashtable.Values.CopyTo
.
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 */
~Hashtable(); |
public virtual IDictionaryEnumerator GetEnumerator(); |
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.
key
Exception Type | Condition |
---|---|
ArgumentNullException | key is null. |
public virtual int GetHashCode(); |
public virtual void GetObjectData( |
info
context
Exception Type | Condition |
---|---|
ArgumentNullException | info is null. |
public Type GetType(); |
item
key
Exception Type | Condition |
---|---|
ArgumentNullException | item is null. -or- key is null. |
item.Equals(key)
.
protected object MemberwiseClone(); |
public virtual void OnDeserialization( |
sender
Exception Type | Condition |
---|---|
SerializationException | The SerializationInfo object associated with the current Hashtable is invalid. |
public virtual void Remove( |
key
Exception Type | Condition |
---|---|
ArgumentNullException | key is null. |
NotSupportedException | The Hashtable is read-only. -or- The Hashtable has a fixed size. |
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 */
table
Exception Type | Condition |
---|---|
ArgumentNullException | table is null. |
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. } }
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. */
IEnumerator IEnumerable.GetEnumerator(); |
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.
public virtual string ToString(); |