Hashtable Class

namespace System.Collections
public sealed class Hashtable : ICollection, IDictionary, IEnumerable

Overview

The Hashtable class represents a collection of strongly typed keys and values that are organized by hash code. It is an unsorted collection of key/value pairs that can be accessed using the key. The Hashtable class is a non-generic collection. For a generic equivalent, use the System.Collections.Generic.Dictionary<TKey, TValue> class.

Key Features

  • Stores key/value pairs.
  • Keys must be unique.
  • Access elements by their key.
  • Elements are not ordered.
  • Allows null keys and values (though generally discouraged).
  • Uses hash codes for efficient lookups.

Common Use Cases

  • Mapping unique identifiers to data objects.
  • Caching frequently accessed data.
  • Implementing lookup tables.
  • Storing configuration settings.

Basic Usage Example

using System;
using System.Collections;

public class Example
{
    public static void Main()
    {
        // Create a Hashtable
        Hashtable studentGrades = new Hashtable();

        // Add elements
        studentGrades.Add("Alice", 95);
        studentGrades.Add("Bob", 88);
        studentGrades.Add("Charlie", 72);

        // Access elements by key
        int aliceGrade = (int)studentGrades["Alice"];
        Console.WriteLine($"Alice's grade: {aliceGrade}"); // Output: Alice's grade: 95

        // Check if a key exists
        if (studentGrades.ContainsKey("Bob"))
        {
            Console.WriteLine("Bob's grade is available.");
        }

        // Remove an element
        studentGrades.Remove("Charlie");

        // Iterate through the Hashtable
        Console.WriteLine("\nRemaining Grades:");
        foreach (DictionaryEntry entry in studentGrades)
        {
            Console.WriteLine($"{entry.Key}: {entry.Value}");
        }
    }
}

Important Considerations

  • Type Safety: Since Hashtable is a non-generic collection, you need to cast values when retrieving them, which can lead to runtime errors if the types are incompatible. Consider using System.Collections.Generic.Dictionary<TKey, TValue> for type safety.
  • Performance: For large collections, the overhead of boxing/unboxing primitive types can impact performance. Generic collections are generally more performant.
  • Hashing: The performance of a Hashtable depends heavily on the quality of the hash codes generated by the keys. Poor hash code distribution can lead to frequent collisions and degraded performance.

See Also