;

C# Hashtable


The Hashtable in C# is a powerful collection type that allows you to store key-value pairs with efficient lookups based on keys. It is part of the System.Collections namespace and is an older non-generic data structure, but it’s still commonly used in scenarios where quick key-based lookups are required. In this tutorial, we’ll explore the details of Hashtable, including examples, use cases, and a real-world example to demonstrate its practicality.

Introduction to Hashtable

The Hashtable collection in C# is a non-generic collection, meaning it can store any type of object as both keys and values. It uses hash codes to store data and allows for fast retrieval based on these keys. Unlike dictionaries in the System.Collections.Generic namespace, Hashtable does not enforce type constraints, making it both flexible and potentially error-prone when used with mixed data types.

Key Features

  • Fast Lookups: Quick access and retrieval of values based on hash codes.
  • Non-Generic: Allows any type of object for both keys and values.
  • Unique Keys: Each key in the hashtable must be unique.
  • Flexible Data Storage: Can store various data types, although consistent data types for keys and values are recommended for clarity and safety.

Creating and Initializing a Hashtable

You can create a Hashtable in C# by initializing an instance of it. The most basic way to create a Hashtable is simply to declare it and then add key-value pairs.

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        // Creating an empty Hashtable
        Hashtable productPrices = new Hashtable();

        // Initializing a Hashtable with initial values
        Hashtable students = new Hashtable
        {
            { "Alice", 90 },
            { "Bob", 85 },
            { "Charlie", 88 }
        };
    }
}

Adding, Accessing, and Updating Elements

Adding Elements

You can add elements to a Hashtable using the Add method. Each key must be unique; otherwise, an exception will be thrown.

productPrices.Add("Laptop", 1500);
productPrices.Add("Tablet", 600);

Accessing Elements

You can access elements by their keys. If the key doesn’t exist, a KeyNotFoundException will be thrown.

int laptopPrice = (int)productPrices["Laptop"]; // Output: 1500
Console.WriteLine($"Laptop Price: {laptopPrice}");

Updating Elements

Updating an element’s value is as simple as assigning a new value to an existing key.

productPrices["Laptop"] = 1400; // Update laptop price to 1400

Removing Elements

To remove an element, use the Remove method. You can also clear the entire Hashtable with Clear.

productPrices.Remove("Tablet"); // Removes the "Tablet" entry
productPrices.Clear(); // Clears all entries

Real-World Example: Product Inventory Management

Consider a scenario where you manage an inventory of products in a retail store. Each product has a unique SKU (Stock Keeping Unit) as its identifier, and the price is stored as the value. This is an ideal use case for a Hashtable, allowing you to quickly look up and update product prices by SKU.

Example

using System;
using System.Collections;

public class Inventory
{
    private Hashtable productInventory = new Hashtable();

    public void AddProduct(string sku, decimal price)
    {
        if (!productInventory.ContainsKey(sku))
        {
            productInventory.Add(sku, price);
            Console.WriteLine($"Product with SKU {sku} added at price {price:C}");
        }
        else
        {
            Console.WriteLine($"Product with SKU {sku} already exists.");
        }
    }

    public void UpdatePrice(string sku, decimal newPrice)
    {
        if (productInventory.ContainsKey(sku))
        {
            productInventory[sku] = newPrice;
            Console.WriteLine($"Product with SKU {sku} updated to new price {newPrice:C}");
        }
        else
        {
            Console.WriteLine($"Product with SKU {sku} not found.");
        }
    }

    public void DisplayInventory()
    {
        Console.WriteLine("\nProduct Inventory:");
        foreach (DictionaryEntry entry in productInventory)
        {
            Console.WriteLine($"SKU: {entry.Key}, Price: {entry.Value:C}");
        }
    }
}

public class Program
{
    public static void Main()
    {
        Inventory inventory = new Inventory();

        // Adding products
        inventory.AddProduct("A101", 1200m);
        inventory.AddProduct("B202", 650m);

        // Displaying inventory
        inventory.DisplayInventory();

        // Updating a product's price
        inventory.UpdatePrice("A101", 1150m);

        // Displaying inventory again
        Console.WriteLine("\nAfter updating price:");
        inventory.DisplayInventory();
    }
}

Explanation

  1. Class Definition: The Inventory class encapsulates a Hashtable to store product SKUs and their prices.
  2. Adding Products: The AddProduct method checks if the SKU already exists before adding it to avoid duplicates.
  3. Updating Prices: The UpdatePrice method ensures the SKU exists before updating its price.
  4. Displaying Inventory: The DisplayInventory method iterates through the Hashtable and prints each SKU and price.

This structure makes it simple to manage product prices in a retail setting where each product has a unique identifier.

Key Takeaways

  • Fast Lookup by Key: Hashtable provides a quick way to retrieve values based on unique keys.
  • Non-Generic Collection: It can store any data type, but consistent use of types improves clarity and safety.
  • Unique Keys Requirement: Each key in the hashtable must be unique, or an exception will be thrown.
  • Ideal for Lookup Scenarios: Works well for settings like inventories, configurations, and mappings where key-based access is essential.

Summary

The Hashtable collection in C# is a versatile and efficient tool for storing and managing key-value pairs, especially useful in situations where fast retrieval is necessary. Though older and non-generic, Hashtable still serves well in contexts like inventory management, configuration storage, and data mapping. By understanding its operations—adding, accessing, updating, and removing elements—developers can leverage Hashtable effectively in various applications. Whether handling product inventories, storing settings, or managing mappings, Hashtable remains a valuable resource for efficient data management in C#.