Skip to main content
Published on

Hashtable Class in C#

Share:

Introduction

In programming, choosing the right data structure can be the difference between an efficient and an inefficient program. The Hashtable class is one of those versatile structures in C# that offers efficiency in search operations.

Why Use the Hashtable?

Unlike other data structures, the Hashtable stores elements in key-value pairs, making it easy to quickly retrieve values. Keys are used to access their corresponding values, similar to a real dictionary where you look up a word (key) to find its definition (value).

Key Features:

  1. Key-Value Storage: Allows retrieving a value directly by its key, rather than searching sequentially.
  2. Unique Keys: Prevents duplicates and ensures data integrity.
  3. Search Efficiency: Using the key's hash code makes search operations extremely fast.

The Hashtable in Action

Let's see how to implement and use the Hashtable in C#:

using System;
using System.Collections;

namespace Base {
  class HashtableClass {
    private Hashtable people = new Hashtable() {
      { "Nelson Silva", 28 },
      { "Larissa Fernandes", 37 }
    };

    public void Run() {
      people.Add("Pedro Henrique", 52);
      people.Add("Raquel Soares", 68);

      people["Pedro Henrique"] = 100;
      people.Remove("Larissa Fernandes");
      people.Clear();

      Console.WriteLine($"Number of people: {people.Count}");

      foreach (DictionaryEntry person in people) {
        Console.WriteLine($"Name: {person.Key}");
        Console.WriteLine($"Age: {person.Value}");
      }
    }
  }
}

When to Use and When Not to Use

Advantages:

  • Fast Access: For scenarios that require frequent retrievals, the Hashtable is ideal.
  • Flexibility: Accepts different types of objects as key or value.

Limitations:

  • No Guaranteed Order: Elements inserted into the Hashtable do not maintain a specific order.
  • Boxing and Unboxing: Since it is not generic, it can suffer from related performance issues.
  • Unique Keys: Attempts to insert duplicate keys result in exceptions.

Tips for Efficient Use

  • Prefer using Dictionary<TKey, TValue> if you know the data types in advance, as it is a generic collection and can avoid the overhead of boxing and unboxing.
  • Always check for the existence of a key before inserting, to avoid exceptions.
  • Consider using a SortedDictionary or SortedList if the order of elements is important.

Conclusion

The Hashtable class is a powerful tool in C#. However, like any data structure, it is essential to know its strengths and limitations. By mastering its characteristics, you can optimize your code and make your programs more efficient.

Happy coding!