C# HashTable Collection Tutorial

In this tutorial we learn about the Hashtable collection in C# that stores its values in key/value pairs.

We cover how to declare an initialize a hashtable, access its values with a the indexer or loops and how to add values with the Add() function.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is a Hashtable

A Hashtable in C# is a collection of key/value pairs. Instead of being organized by the key, a Hashtable is organized by the hash code of the key.

We don’t recommend using this type as it is an older .NET Framework type. It is slower than the generic Dictionary type, which we recommend instead.

However, if you’re working on an older program that still uses a Hashtable, it’s helpful to know how to use it.

The Hashtable namespace

A Hashtable, as a non-generic collection class, is defined in the System.Collections namespace. Before we can use a Hashtable, we must specify this namespace at the top of the document.

Example:
using System;
using System.Collections;

How to declare a Hashtable

A Hashtable is declared or initialized with the new keyword, which will create a new instance of the Hashtable class and store it in the table_name object.

Syntax:
 Hashtable table_name = new Hashtable();
Example:
using System.Collections;

namespace Hashtables
{
    class Program
    {
        static void Main()
        {
            Hashtable hash = new Hashtable();
        }
    }
}

In the example above, we declare a new Hashtable and store it in the hash object.

How to initialize a Hashtable with values

If we know beforehand the values, or some of the values, we want to store in our Hashtable, we can use initialization syntax to add those values when the Hashtable is declared.

Inside the code block of the Hashtable initializer, we add key/value pairs between curly braces, separated by a comma. When adding multiple sets of key/value pairs, we separate each set with a comma as well.

Syntax:
Hashtable table_name = new Hashtable()
{
    { key, value },
    { key, value }
};
Example:
using System.Collections;

namespace Hashtables
{
    class Program
    {
        static void Main()
        {
            Hashtable hash = new Hashtable
            {
                { 1, "One" },
                { 5, "Five" }
            };
        }
    }
}

In the example above, we add 2 entries to our Hashtable. The first entry has a key of 1 and a value of “One”, the second entry has a key of 5 and a value of “Five”.

When accessing these values, we would use the keys 1 and 5 to access their corresponding values.

How to assign values to a Hashtable with the indexer

To add a value to a Hashtable with the indexer, we use square brackets after the Hashtable name.

Because a Hashtable works with key/value pairs, we have to specify both a key and a value. The key is specified between square brackets.

Syntax:
table_name[key] = value;
Example:
using System.Collections;

namespace Hashtables
{
    class Program
    {
        static void Main()
        {
            Hashtable hash = new Hashtable();

            hash[1] = "One";
            hash[5] = "Five";
            hash[30] = "Thirty";
        }
    }
}

In the example above, we add new values to an empty Hashtable with the indexer. The 1, 5 and 30 are the keys and the “One”, “Five” and “Thirty” are the values that correspond to each key respectively.

How to assign values to a Hashtable with the Add() method

The Add() function adds an item to the Hashtable with a key and a value.

To use the Add() function we specify the name of the Hashtable followed by a dot and the Add() function. As parameters the Add() function takes first a key and then the corresponding value, separated by a comma.

Syntax:
table_name.Add(key, value);
Example:
using System.Collections;

namespace Hashtables
{
    class Program
    {
        static void Main()
        {
            Hashtable hash = new Hashtable();

            hash.Add(1, "One");
            hash.Add(5, "Five");
            hash.Add("Thirty", 30);
            hash.Add(3.14f, 3.14);
            hash.Add(99, null);
        }
    }
}

In the example above we add multiple key/value pairs with the Add() function.

A key and value can be of any type, as seen in the example above. However, a key is not allowed to be null whereas a value is allowed to be null.

Example:
hash.Add(1, null);
hash.Add(null, "Error"); // illegal

How to access single values in a Hashtable with the indexer

To access a single value in a Hashtable we can use the indexer with the key that corresponds to the value we want.

Syntax:
table_name[key]
Example:
using System;
using System.Collections;

namespace Hashtables
{
    class Program
    {
        static void Main()
        {
            Hashtable hash = new Hashtable();

            hash.Add(1, "One");

            Console.WriteLine(hash[1]);
            Console.ReadLine();
        }
    }
}

In the example above, we access the value at key 1 and print it out to the console.

How to access multiple values in a Hashtable with a loop

To access multiple values in a Hashtable we can use a loop. In this case we use a foreach loop.

Example:
using System;
using System.Collections;

namespace Hashtables
{
    class Program
    {
        static void Main()
        {
            Hashtable hash = new Hashtable();

            hash.Add(1, "One");
            hash.Add(5, "Five");
            hash.Add("Thirty", 30);
            hash.Add(3.14f, 3.14);
            hash.Add(99, null);

            foreach(DictionaryEntry entry in hash)
            {
                Console.WriteLine("Key: {0} | Value: {1}", entry.Key, entry.Value);
            }

            Console.ReadLine();
        }
    }
}

In the example above, we use DictionaryEntry as a type, which is a struct that defines a dictionary key/value pair. This allows us to use entry.Key and entry.Value to access the key/value pairs.

We haven’t learned about structs or dictionaries yet so don’t worry about it right now, just know that we can use DictionaryEntry as a type to access the keys and values through dot notation.

A list of common properties of the Hashtable class

The following table lists some of the commonly used properties of the Hashtable class:

PropertyDescription
CountGets the number of key/value pairs in a Hashtable
ItemGets or sets the value associated with a specified key
KeysGets an ICollection containing the keys in a Hashtable
ValuesGets an ICollection containing the values in a Hashtable

A list of common methods of the Hashtable class

The following table lists some of the commonly used methods of the Hashtable class:

MethodDescription
Add(key, value)Adds an element with the specified key and value into the Hashtable
ContainsKey(key)Checks if the Hashtable contains a specified key
ContainsValue(value)Check is the Hashtable contains a specified value
Remove(key)Removes an element from the Hashtable with the specified key
Clear()Removes all elements from the Hashtable

Summary: Points to remember

  • A Hashtable is an older collection type. It’s recommended to use a generic Dictionary collection instead of a Hashtable. This tutorial is only here in case you find a Hashtable in older code and have to work with it.