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.
HashtableThe 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.
HashtableYou 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 }
};
}
}
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);
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 an element’s value is as simple as assigning a new value to an existing key.
productPrices["Laptop"] = 1400; // Update laptop price to 1400
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
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.
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();
}
}
Hashtable to store product SKUs and their prices.AddProduct method checks if the SKU already exists before adding it to avoid duplicates.UpdatePrice method ensures the SKU exists before updating its price.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.
Hashtable provides a quick way to retrieve values based on unique keys.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#.