
Hashtable optimizes lookups. This type is used in the C# language. It computes a hash of each key you add. It then uses this hash code to look up the element very quickly. It is an older .NET Framework type. It is slower than the generic Dictionary type.
This C# Hashtable tutorial demonstrates important methods. Hashtable provides fast lookups of keys.

First, you can create a new Hashtable with the simplest constructor. When it is created, the Hashtable has no values. We directly assign values with the indexer, which uses the square brackets [ ]. The example adds three integer keys with one string value each.
Add entries to Hashtable and display them [C#]
using System;
using System.Collections;
class Program
{
static void Main()
{
Hashtable hashtable = new Hashtable();
hashtable[1] = "One";
hashtable[2] = "Two";
hashtable[13] = "Thirteen";
foreach (DictionaryEntry entry in hashtable)
{
Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
}
}
}
Result
13, Thirteen
2, Two
1, OneDescription. The program displays all the DictionaryEntry objects returned from the enumerator in the foreach loop. The WriteLine call contains a format string that displays the key/value pairs with a comma.

You can loop through the Hashtables by using the DictionaryEntry type in a foreach loop. Alternatively you can get the Keys collection and copy it into an ArrayList. The DictionaryEntry collection contains two objects: the key and the value. You need to cast these.
Note: Please see the section on casting below.
Continuing on, we see some of the most common and important instance methods on the Hashtable. You will want to call ContainsKey on your Hashtable with the key contents. This method returns true if the key is found, regardless of the value. Contains works the same way. Finally we see an example of using the indexer with the [ ] square brackets.
Program that uses Contains method [C#]
using System;
using System.Collections;
class Program
{
static Hashtable GetHashtable()
{
// Create and return new Hashtable.
Hashtable hashtable = new Hashtable();
hashtable.Add("Area", 1000);
hashtable.Add("Perimeter", 55);
hashtable.Add("Mortgage", 540);
return hashtable;
}
static void Main()
{
Hashtable hashtable = GetHashtable();
// See if the Hashtable contains this key.
Console.WriteLine(hashtable.ContainsKey("Perimeter"));
// Test the Contains method. It works the same way.
Console.WriteLine(hashtable.Contains("Area"));
// Get value of Area with indexer.
int value = (int)hashtable["Area"];
// Write the value of Area.
Console.WriteLine(value);
}
}
Output
True
True
1000Indexer note. An indexer is a property that receives an argument inside square brackets. The Hashtable implements indexers. It returns plain objects so you must cast them. Please see the casting section for more information on this.
Indexer ExamplesNext, we see how you can add multiple types to your Hashtable. This is interesting and is very different from Dictionary generic collections. The example here adds string keys and int keys. Each of the key/value pairs has different types. You can put them all in the same Hashtable.
Program that uses multiple types [C#]
using System;
using System.Collections;
class Program
{
static Hashtable GetHashtable()
{
Hashtable hashtable = new Hashtable();
hashtable.Add(300, "Carrot");
hashtable.Add("Area", 1000);
return hashtable;
}
static void Main()
{
Hashtable hashtable = GetHashtable();
string value1 = (string)hashtable[300];
Console.WriteLine(value1);
int value2 = (int)hashtable["Area"];
Console.WriteLine(value2);
}
}
Output
Carrot
1000
This code might throw exceptions. Casting is a delicate operation and can raise exceptions. If the cast was applied to a different type, the statement could throw an InvalidCastException. You can avoid this by using the 'is' or 'as' statements.
You can avoid casting problems with your Hashtable. You can use the 'as' operator to attempt to cast an object to a specific reference type. If the cast doesn't succeed, the result will be null. On the other hand, you can use the 'is' operator. The is operator returns true or false based on the result.
Is Cast Example As Cast ExampleProgram that casts Hashtable values [C#]
using System;
using System.Collections;
using System.IO;
class Program
{
static void Main()
{
Hashtable hashtable = new Hashtable();
hashtable.Add(400, "Blazer");
// This cast will succeed.
string value = hashtable[400] as string;
if (value != null)
{
Console.WriteLine(value);
}
// This cast won't succeed, but won't throw.
StreamReader reader = hashtable[400] as StreamReader;
if (reader != null)
{
Console.WriteLine("Unexpected");
}
// You can get the object and test it.
object value2 = hashtable[400];
if (value2 is string)
{
Console.Write("is string: ");
Console.WriteLine(value2);
}
}
}
Output
Blazer
is string: Blazer
What's the best way to cast? You can reduce the number of casts and improve performance by using the 'as' operator. This is one performance warning that FxCop, a static analysis tool from Microsoft, will give you.
FxCop Performance WarningsNext, we see how you can get all of the keys or values in your Hashtable. This enables you to loop over these values, and also to store them in a separate ArrayList collection. This example shows all the keys, then all the values, and then stores the keys in an ArrayList.
Note: This C# Hashtable example uses the Keys property. This property returns all the keys.
Loop over Keys, Values and store in ArrayList [C#]
using System;
using System.Collections;
class Program
{
static void Main()
{
Hashtable hashtable = new Hashtable();
hashtable.Add(400, "Blaze");
hashtable.Add(500, "Fiery");
hashtable.Add(600, "Fire");
hashtable.Add(800, "Immolate");
// Display the keys.
foreach (int key in hashtable.Keys)
{
Console.WriteLine(key);
}
// Display the values.
foreach (string value in hashtable.Values)
{
Console.WriteLine(value);
}
// Put keys in an ArrayList.
ArrayList arrayList = new ArrayList(hashtable.Keys);
foreach (int key in arrayList)
{
Console.WriteLine(key);
}
}
}
Output
800 (First loop)
600
500
400
Immolate (Second loop)
Fire
Fiery
Blaze
800 (Third loop)
600
500
400
Looping over keys. The first loop in the program loops over the collection returned by the Keys instance property on the Hashtable instance. You can use the foreach loop as shown here for the simplest syntax.
Looping over values. The second loop in the program shows how you can enumerate only the values in the Hashtable instance. The four words stored in the Hashtable as values will be printed to the screen.
Storing in ArrayList. Finally the example shows how you can create a new ArrayList with the copy constructor and pass it the Keys (or Values) property as the argument. After the ArrayList constructor executes, the ArrayList can be enumerated to see all the values.
ArrayList Tips
Tip. The Keys and Values public accessors provide an easy way to get a collection of the keys and values in the Hashtable at the time they are accessed. If you need to look at all the keys and values in pairs, it is best to enumerate the Hashtable instance itself.
You can count the number of elements in your Hashtable with the Count property. Additionally, the example shows using the Clear method to erase all the Hashtable contents. An alternative to Clear is simply to reassign your Hashtable reference to a new Hashtable().
Note: This C# Hashtable example shows how you can use the Count property. This property returns the number of elements.
Program that uses Count on Hashtable [C#]
using System;
using System.Collections;
class Program
{
static void Main()
{
// Add four elements to Hashtable.
Hashtable hashtable = new Hashtable();
hashtable.Add(1, "Sandy");
hashtable.Add(2, "Bruce");
hashtable.Add(3, "Fourth");
hashtable.Add(10, "July");
// Get Count of Hashtable.
int count = hashtable.Count;
Console.WriteLine(count);
// Clear the Hashtable.
hashtable.Clear();
// Get Count of Hashtable again.
Console.WriteLine(hashtable.Count);
}
}
Output
4
0Description. First the program adds four keys with four values to the Hashtable instance. Then it captures the Count, which is 4. It then uses Clear on the Hashtable, which now has 0 elements. The Hashtable is empty but not null.

Count property on Hashtable. The Hashtable class in System.Collections implements a public instance property accessor that returns the number of elements in the Hashtable. The Count property does not need to perform lengthy computations or loops to return the count. MSDN states that "retrieving the value of this property is an O(1) operation."
Constant time. This property is a constant-time accessor of the Hashtable's internal element count. We saw an example of how it will report that a Hashtable has several actual elements in its buckets (or zero). The property returns an integer and is a simple accessor with low resource demands.

Let's look at a benchmark of the Hashtable collection in the System.Collections namespace, versus the Dictionary collection in the System.Collections.Generic namespace. The benchmark first populates an equivalent version of each collection. Then it tests one key that is found and one that is not found. It repeats this 20 million times.
Hashtable used in benchmark [C#]
Hashtable hashtable = new Hashtable();
for (int i = 0; i < 10000; i++)
{
hashtable[i.ToString("00000")] = i;
}
Dictionary used in benchmark [C#]
var dictionary = new Dictionary<string, int>();
for (int i = 0; i < 10000; i++)
{
dictionary.Add(i.ToString("00000"), i);
}
Statements benchmarked [C#]
hashtable.ContainsKey("09999")
hashtable.ContainsKey("30000")
dictionary.ContainsKey("09999")
dictionary.ContainsKey("30000")
Benchmark of 20 million lookups
Hashtable result: 966 ms
Dictionary result: 673 msInterpretation. The Hashtable code is significantly slower than the Dictionary code. I calculate that Hashtable here is 30% slower. This means that for strongly-typed collections, the Dictionary is faster.

There are 15 overloaded constructors in the Hashtable class. These provide ways to specify capacities, and let you copy existing collections into the Hashtable. Additionally, you can specify how the hash code is computed and how keys are compared.
Constructor Tips
We saw how you can use the Hashtable collection in the .NET Framework and the C# language. This is an older collection that is essentially obsoleted by the Dictionary collection. Knowing how to use it is critical when maintaining older programs. These programs are important to many organizations.
Dictionary Examples Collections