How to Work With Hashtable in C# with Example?

A C# hashtable is a collection that stores key-value pairs, allowing users to quickly retrieve values based on unique keys. In C#, the Hashtable class from the System.Collections namespace is used for this purpose. In this C# tutorial, I will explain how to work with Hashtable in C# with examples.

A Hashtable in C# is a collection that stores key-value pairs in a way that makes it easy to retrieve values by their key. It organizes its elements based on the hash code of the key for efficient lookups. Each key in a Hashtable must be unique, and it can contain different types of values, including objects. The Hashtable is found in the System.Collections namespace and is not a generic type, unlike Dictionary<TKey, TValue>.

Introduction to Hashtable in C#

A hashtable is a data structure in C# that stores data in a key-value pair format. It allows for the quick retrieval of data values by using a unique key.

Structure of a Hashtable:

  • Key: A unique object that is used for indexing the values.
  • Value: The data that is associated with a key.

The C# Hashtable class is found in the System.Collections namespace. It can hold items of any data types. To use a hashtable, one must create an instance of the Hashtable class.

Basic Operations:

  • Adding items: Use the Add method, passing the key and value.
  • Removing items: Use the Remove method with the key of the item to delete.
  • Accessing items: Retrieve values by their keys using an indexer.
  • Checking existence: The ContainsKey method checks if a key is present.

Example Usage:

Hashtable hashtable = new Hashtable();
hashtable.Add("ID1", "Item1");
hashtable.Add("ID2", "Item2");
hashtable.Add("ID3", "Item3");

// Retrieve value with key "ID2"
string value = (string)hashtable["ID2"];

// Remove item with key "ID1"
hashtable.Remove("ID1");

In this example, a new hashtable is created, and three key-value pairs are added. The value associated with the key “ID2” is retrieved and stored in a variable. Then, the pair with the key “ID1” is removed from the hashtable.

One must be cautious about two things:

  • Hashtables do not guarantee the order of items.
  • Keys must be unique and cannot be null, while values can be null or duplicates.

Create a Hashtable in C#

In C#, a Hashtable is a collection that stores key-value pairs. It organizes the data for quick searches by keys. The System.Collections namespace provides the Hashtable class.

To begin, one must include the System.Collections namespace:

using System.Collections;

Then, instantiate a Hashtable with the new keyword:

Hashtable hashtable = new Hashtable();

One can add elements with unique keys using the Add method:

hashtable.Add("id", 1);
hashtable.Add("name", "John Doe");

It’s important to note that the keys are case-sensitive and must be unique. However, the values can be duplicates.

If an attempt is made to insert a duplicate key, a System.ArgumentException will be thrown. To handle this, one must ensure the key’s uniqueness before adding it:

if (!hashtable.ContainsKey("id"))
{
    hashtable.Add("id", 2);
}

The Hashtable is dynamic in size, meaning it can automatically resize to accommodate more elements as needed. Though not ordered, it’s optimized for retrieval. When a value is needed, one can retrieve it quickly using its key:

object value = hashtable["name"]; // Retrieves the value for the key "name"

A Hashtable in C# is powerful for managing pairs of related data for quick access using keys. Its uses are vast, from data caching to configuration settings management, making it an essential collection type in C#.

Add Items to a Hashtable in C#

When populating a Hashtable in C#, developers primarily utilize the Add method for new entries and the Item property for managing duplicates.

Using the Add() Method

The Add() method takes two parameters: the key and the value. Each key in a Hashtable must be unique, and attempting to add a duplicate key will result in a System.ArgumentException. Here’s how one can add a simple key-value pair to a Hashtable:

Hashtable hashtable = new Hashtable();
hashtable.Add("Key1", "Value1");

One should ensure that the key is not null as that would cause an ArgumentNullException.

Handling Duplicates with Item Property

To update an existing entry or handle duplicate keys gracefully, the Item property, indexed with the key, can be used. If the key exists, its value will be updated; otherwise, a new key-value pair will be added:

hashtable["Key1"] = "NewValue1"; // Updates the value for "Key1" if it exists

Using the Item property does not throw exceptions for duplicate keys, making it a safer choice for handling potential duplicates.

Retrieve Items from A Hashtable in C#

To efficiently retrieve items from a hashtable in C#, one can utilize the keys or directly access values with the specific key. Understanding these methods ensures optimized data retrieval.

Using the Keys Property

When items need to be retrieved based on their keys, the Keys property of a hashtable is used. It provides a collection of all keys in the hashtable. Iterating over this collection allows one to reference each individual key and subsequently retrieve the corresponding value. Below is an example of using the Keys property:

Hashtable hashtable = new Hashtable();
hashtable.Add("id", 1);
hashtable.Add("name", "John Doe");
hashtable.Add("email", "john@doe.com");

foreach (var key in hashtable.Keys)
{
    // Retrieves the value associated with the key
    Console.WriteLine("Key: {0}, Value: {1}", key, hashtable[key]);
}

Accessing Values with the Item Property

The Item property, also known as the indexer, provides direct access to values in the hashtable by using the associated key. This method is straightforward and does not require iteration when one knows the specific key of the item required. Here’s an example of retrieving an item by key with the Item property:

Hashtable hashtable = new Hashtable();
hashtable.Add("id", 1);
hashtable.Add("name", "John Doe");

// Retrieves the value using the Item property with the key "name"
var name = hashtable["name"];
Console.WriteLine("The name is: " + name);

Iterate Over a Hashtable in C#

In C#, a Hashtable can be navigated through either using a foreach loop or an enumerator. Both methods allow you to access key-value pairs stored in the Hashtable.

Using foreach Loop

The foreach loop provides a convenient way to iterate over all elements in a Hashtable. It gives you access to each DictionaryEntry object which contains both the key and the value.

Hashtable myHashtable = new Hashtable();
myHashtable.Add("ID1", "Value1");
myHashtable.Add("ID2", "Value2");
myHashtable.Add("ID3", "Value3");

foreach (DictionaryEntry entry in myHashtable)
{
    Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
}

In the above snippet, entry.Key and entry.Value are used to access the key and value of each element in the Hashtable.

Enumerator Approach

An enumerator provides explicit control over the iteration by offering methods to MoveNext and Reset, and a property to get the current element as DictionaryEntry.

Hashtable myHashtable = new Hashtable();
myHashtable.Add("ID1", "Value1");
myHashtable.Add("ID2", "Value2");
myHashtable.Add("ID3", "Value3");

IDictionaryEnumerator enumerator = myHashtable.GetEnumerator();

while (enumerator.MoveNext())
{
    DictionaryEntry entry = (DictionaryEntry)enumerator.Current;
    Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
}

When using the enumerator, you explicitly call MoveNext to advance to the next element and check the current element using the Current property.

Remove Items from a Hashtable in C#

Manipulating the contents of a Hashtable in C# is straightforward. One can remove specific items using the Remove method or clear the entire collection with the Clear method.

Remove() Method

The Remove method in a Hashtable requires a key and eliminates the key-value pair associated with that key. It is defined as public virtual void Remove (object key);. To remove an item, one simply passes the corresponding key to the Remove method as shown below.

Hashtable hashtable = new Hashtable();
hashtable.Add("id", 1);
hashtable.Add("name", "John Doe");

// Remove a single item with the key "id"
hashtable.Remove("id");

If the key does not exist in the Hashtable, the method will not throw an exception; it simply does nothing.

Clear() Method

To entirely empty a Hashtable, the Clear method is used. This method does not take any parameters and is invoked directly on the Hashtable instance as follows:

Hashtable hashtable = new Hashtable();
hashtable.Add("id", 1);
hashtable.Add("name", "John Doe");

// Clear all items from the hashtable
hashtable.Clear();

This is especially useful when one needs to reset the Hashtable without creating a new instance. After calling Clear, the Hashtable count becomes 0, effectively removing all entries.

Conclusion

Hash tables in C# provide efficient data retrieval through key-value pairs. They work on the principle of hashing, where a key is mapped to a specific location in the hash table. By utilizing the Hashtable class, developers can implement fast and scalable applications. The following points summarize the effective use of hash tables in C#:

  • Initialization: Developers must initialize the Hashtable object before using it.
  • Adding Items: Items can be added with the Add method by specifying a key and value.
  • Retrieval: The Item property or indexer allows for quick data retrieval using the unique key.
  • Handling Collisions: Hash tables automatically handle collisions, but it’s good practice to account for potential duplicate keys.
  • Performance: For optimal performance, developers should ensure a suitable load factor and consider overriding default hash functions for custom objects.

In this C# tutorial, I have explained how to use Hashtable in C# with Examples.

You may also like: