C# Hashtable

Squares: different patterns

Hashtable optimizes lookups. 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.

Dictionary

Example

Framework: NET

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.

Next:The example adds three integer keys, with one string value each, to the Hashtable object.

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, One

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.

Foreach

Foreach loop construct

You can loop through the Hashtables by using the DictionaryEntry type in a foreach-loop. You can alternatively get the Keys collection and copy it into an ArrayList. A DictionaryEntry contains two objects: the key and the value.

ForeachDictionaryEntry

Contains

We next 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.

Also:Contains works the same way. 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
1000

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.

Indexer

Multiple types

Next, we add multiple types to a Hashtable. 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
Warning: exclamation mark

This code might throw exceptions. Casting is a delicate operation. 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.

Cast

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 does not succeed, the result will be null.

Null

Tip:You can also use the is-operator.
This operator returns true or false based on the result.

IsAs
Program 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
As keyword

With Hashtable, you can reduce the number of casts and improve performance by using the as-operator. This is one performance warning given by FxCop, a static analysis tool from Microsoft.

FxCop

Keys, values

Key: used to access value

We next get all of the keys or values. We can loop over these values, or 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 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
Arrow indicates looping

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 for the simplest syntax.

Looping over values. The second loop in the program shows how to enumerate only the values in the Hashtable instance. The four words stored in the Hashtable as values will be printed to the screen.

Console.WriteLine

Storing in ArrayList. The example creates 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.

ArrayListProgramming tip

Tip:The Keys and Values public accessors return a collection of the keys and values in the Hashtable at the time they are accessed.

However:If you need to look at all the keys and values in pairs, it is best to enumerate the Hashtable instance itself.

Count, Clear

Pound symbol

You can count the elements in a Hashtable with the Count property. The example also shows using the Clear method to erase all the Hashtable contents. An alternative is to reassign your Hashtable reference to a new Hashtable().

Note:This example shows how to 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
0

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.

Property

Count property on Hashtable. The Hashtable class implements a public instance property accessor that returns the number of elements in the Hashtable. The Count property does not perform lengthy computations or loops.

Note:MSDN states that, for Count, "retrieving the value of this property is an O(1) operation."

Constant time. This property is a constant-time accessor. It will report that a Hashtable has several actual elements in its buckets (or zero). It returns an integer and is a simple accessor with low resource demands.

Benchmark

Performance optimization

Continuing on, we test the Hashtable collection in the System.Collections namespace against 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 ms

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.

Constructors

New keyword, constructor invocation

There are 15 overloaded constructors in the Hashtable class. These provide ways to specify capacities. They let you copy existing collections into the Hashtable. You can also specify how the hash code is computed.

Constructor

Summary

We used the Hashtable collection. This is an older collection that is obsoleted by the Dictionary collection. Knowing how to use it is critical when maintaining older programs. These programs are important to many organizations.


C#: Collections