You want to use the Hashtable collection in the best way, for either an older program written in the C# language or for maintaining a program. The Hashtable provides a fast and simple interface, in many ways simpler than Dictionary. Here we see how you can use the Hashtable collection in the C# programming language, providing a fast lookup collection for hashing keys to values in a constant-time data structure.
=== Hashtable lookup benchmark === Hashtable result: 966 ms Dictionary result: 673 ms
First here we see how you can create a new Hashtable with the simplest, parameterless constructor. When it is created, the Hashtable has no values, but we can 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 of the program ===
13, Thirteen
2, Two
1, OneDescription of the output. 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. Please see the section on casting below.
Here 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 methods 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.
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")); // <-- True
// Test the Contains method. It works the same way.
Console.WriteLine(hashtable.Contains("Area")); // <-- True
// Get value of Area with indexer.
int value = (int)hashtable["Area"];
// Write the value of Area.
Console.WriteLine(value); // <-- 1000
}
}Note on the indexer. In C#, an indexer is a property that receives an argument inside square brackets. The Hashtable implements indexers, but it returns plain objects, so you must cast them. See below section for more information on casting. You can find more information on indexers here.
Here 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.
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); // <-- Carrot
int value2 = (int)hashtable["Area"];
Console.WriteLine(value2); // <-- 1000
}
}This code might throw exceptions. In C#, 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.
Here we see ways 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, which returns true or false based on the result.
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);
}
}
}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.
(See FxCop Performance Warnings.)
Here we note that the Hashtable collection in the C# programming language provides two powerful property accessors that let you access all the keys and values in the collection at once. The properties are called Keys and Values and more information about these properties is available on this website.
(See Hashtable Keys and Values.)
Here we mention that the Hashtable collection has a useful Count property accessor that will retrieve and return the number of valid elements in the Hashtable's internal buckets. The Count property is shown in a separate article on this site, along with the Clear method, which is used to show how the Count changes.
(See Hashtable Count Property.)
Here we 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 ===
Hashtable hashtable = new Hashtable();
for (int i = 0; i < 10000; i++)
{
hashtable[i.ToString("00000")] = i;
}
=== Dictionary used in benchmark ===
var dictionary = new Dictionary<string, int>();
for (int i = 0; i < 10000; i++)
{
dictionary.Add(i.ToString("00000"), i);
}
=== Statements benchmarked ===
hashtable.ContainsKey("09999")
hashtable.ContainsKey("30000")
dictionary.ContainsKey("09999")
dictionary.ContainsKey("30000")
=== Benchmark of 20 million lookups ===
See results at top.Interpretation of the benchmark. The Hashtable code is significantly slower than the Dictionary code. The author calculates 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 in .NET 3.5 SP1. 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.
Here 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, but knowing how to use it is critical when maintaining older programs, which are likely important to your organization. Finally, we saw that the Hashtable has worse performance than Dictionary.