C# Hashtable: Get Value by Key
The Hashtable class in C# is a non-generic collection that stores key-value pairs. To retrieve values efficiently, you can access them directly using the key. This article explains how to retrieve values from a Hashtable in C# using different approaches.
Accessing Values by Key
Using Indexer Syntax
The simplest way to access values in a Hashtable is by using the indexer syntax hashtable[key]. This method will return the value associated with the specified key. However, if the key is not found, this will return null.
using System;
using System.Collections;
public class HashtableIndexerExample
{
public static void Main()
{
// Create a Hashtable and populate it with key-value pairs
Hashtable employees = new Hashtable
{
{ "E101", "John Doe" },
{ "E102", "Jane Smith" },
{ "E103", "Mary Johnson" }
};
// Retrieve values using indexer syntax
Console.WriteLine($"Employee E101: {employees["E101"]}");
Console.WriteLine($"Employee E102: {employees["E102"]}");
// Handle a missing key gracefully
object missingEmployee = employees["E200"];
if (missingEmployee == null)
{
Console.WriteLine("Employee E200 not found.");
}
}
}
Using ContainsKey Method
To safely check if a key exists before retrieving its value, you can use the ContainsKey method. This approach helps prevent errors when accessing non-existent keys.
using System;
using System.Collections;
public class HashtableContainsKeyExample
{
public static void Main()
{
// Create a Hashtable with some initial data
Hashtable products = new Hashtable
{
{ "P001", "Laptop" },
{ "P002", "Smartphone" },
{ "P003", "Tablet" }
};
// Safely check if a key exists before accessing its value
string key = "P002";
if (products.ContainsKey(key))
{
Console.WriteLine($"Product {key}: {products[key]}");
}
else
{
Console.WriteLine($"Product {key} not found.");
}
// Attempt to access a non-existent key
key = "P999";
if (!products.ContainsKey(key))
{
Console.WriteLine($"Product {key} not found.");
}
}
}
Best Practices
- Check for Existence: Use ContainsKey to verify the key before accessing it to avoid potential errors.
- Null Handling: Handle null values gracefully since Hashtable allows storing them.
- Type Safety: When retrieving objects, always cast them to the appropriate data type.
Conclusion
Retrieving values from a Hashtable in C# is straightforward using indexer syntax or the ContainsKey method. By following best practices, you can efficiently and safely access values by key while preventing runtime errors.