C# Non-Generic Hashtable

A non-generic hashtable in C# store data in key and value pairs. Similarly to a non-generic arraylist, neither the keys or the values have to be of the same type and the size does not need to be specified when they are declared. The key and value pairs in a hashtable are organised based on a hash code of the key, instead of new items being added to the bottom or stored alphabetically. A key must be unique and cannot be null, whilst the value can be null and does not need to be unique.

The example below shows the declaration of a hashtable, with four items added to it using the 'Add' method. All of the keys are strings, containing a person's name, whilst all the values are numeric, comprising of an age, corresponding to the name in the key.

Hashtable people = new Hashtable();

people.Add("Bob Smith", 30);
people.Add("George Jones", 21);
people.Add("Fred Bloggs", 43);
people.Add("Alan White", 29);

The declaration and initialisation can be combined into one statement, so the above could be re-written as follows.

Hashtable people = new Hashtable()
{
    {"Bob Smith", 30},
    {"George Jones", 21},
    {"Fred Bloggs", 43},
    {"Alan White", 29}
};

Regardless of the method used to declare and initialise the hashtable, a 'foreach' loop can be used to process its contents. Here, the key and value for each person are incorporated in to a sentence stating a person’s age. The curly braces that contain a number are placeholders for the key and value of the hashtable.

foreach (DictionaryEntry person in people)
{
    Console.WriteLine("{0} is {1} years old.", person.Key, person.Value);
}

The output in the console from the above example is as follows. Notice that the order of the items differs from how they were added to the hashtable.

George Jones is 21 years old.
Bob Smith is 30 years old.
Fred Bloggs is 43 years old.
Alan White is 29 years old.

It is also possible to access a single value if the key is known.

Console.WriteLine(people["Bob Smith"]);

If it is necessary to find out how many key and value pairs exist in a hashtable, then the 'Count' property can be used to achieve this.

Console.WriteLine(people.Count);

This could be utilised, for example, if an ordinary 'for' loop were to be used, instead of a 'foreach' loop.

In order to check whether a specific key or value exists in a hashtable, the 'ContainsKey' and 'ContainsValue' methods can be used, both of which return a Boolean 'True' or 'False' value.

Console.WriteLine(people.ContainsKey("Fred Bloggs"));
Console.WriteLine(people.ContainsValue(29));

As well as adding new items using the 'Add' method, there is also a 'Remove' method, to remove a specific key and value pair, if the key is known.

people.Remove("Fred Bloggs");

To remove all values in a hashtable, instead of removing each key and value pair, one at a time, using the 'Remove' method, there is a 'Clear' method that will achieve this in one statement.

people.Clear();

Further Reading