How to Implement Hash Table in C# - Simple Guide
In C#, you can implement a hash table using the built-in
Dictionary<TKey, TValue> class which stores key-value pairs with fast lookup. Alternatively, you can create a custom hash table by using an array of buckets and handling collisions with chaining or open addressing.Syntax
The basic syntax to declare a hash table using the built-in Dictionary<TKey, TValue> is:
Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();creates a new dictionary.dict.Add(key, value);adds a key-value pair.dict[key]accesses the value by key.
For a custom implementation, you define an array of buckets and implement methods to add, find, and remove items using a hash function.
csharp
Dictionary<string, int> dict = new Dictionary<string, int>(); dict.Add("apple", 5); int value = dict["apple"];
Example
This example shows how to use the built-in Dictionary<string, int> as a hash table to store and retrieve values by keys.
csharp
using System; using System.Collections.Generic; class Program { static void Main() { Dictionary<string, int> hashTable = new Dictionary<string, int>(); // Add key-value pairs hashTable.Add("apple", 10); hashTable.Add("banana", 20); hashTable.Add("orange", 30); // Access value by key Console.WriteLine("Value for 'apple': " + hashTable["apple"]); // Check if key exists if (hashTable.ContainsKey("banana")) { Console.WriteLine("Value for 'banana': " + hashTable["banana"]); } // Iterate over all key-value pairs foreach (var pair in hashTable) { Console.WriteLine(pair.Key + ": " + pair.Value); } } }
Output
Value for 'apple': 10
Value for 'banana': 20
apple: 10
banana: 20
orange: 30
Common Pitfalls
Common mistakes when using hash tables in C# include:
- Trying to add a key that already exists causes an exception. Use
ContainsKeyto check before adding. - Accessing a key that does not exist throws a
KeyNotFoundException. UseTryGetValueto safely get values. - Using mutable objects as keys can cause unexpected behavior because their hash code may change.
csharp
/* Wrong way: Adding duplicate key throws exception */ Dictionary<string, int> dict = new Dictionary<string, int>(); dict.Add("key1", 1); dict.Add("key1", 2); // Throws exception /* Right way: Check before adding */ if (!dict.ContainsKey("key1")) { dict.Add("key1", 2); } /* Safe access using TryGetValue */ if (dict.TryGetValue("key2", out int value)) { Console.WriteLine(value); } else { Console.WriteLine("Key not found"); }
Quick Reference
Here is a quick summary of common Dictionary<TKey, TValue> methods:
| Method | Description |
|---|---|
| Add(key, value) | Adds a new key-value pair; throws if key exists. |
| ContainsKey(key) | Checks if the key exists. |
| TryGetValue(key, out value) | Tries to get value safely without exception. |
| Remove(key) | Removes the key-value pair if it exists. |
| Clear() | Removes all key-value pairs. |
Key Takeaways
Use C#'s built-in Dictionary for efficient hash table implementation.
Always check if a key exists before adding to avoid exceptions.
Use TryGetValue to safely access values without risking exceptions.
Avoid using mutable objects as keys to prevent hash code issues.
Dictionary provides fast lookup, insertion, and removal by key.