C# Hashtable

C# collections

In C#, a hash table (Hashtable) is a collection of key-value pairs (key=>value) a collection that stores data in the form, where keys and values can be any objects.

Each item in the hash table has akey=>valueYes, the key is used to access items in the collection.

Hash tables organize and access data based on hash algorithms, providing efficient lookup, insertion, and deletion operations.

Hashtableis a non-generic collection, located in the namespaceSystem.Collectionsin. If a generic version is needed, you can useDictionary<TKey, TValue>。

Basic structure:

  • Key(Key): used to identify each data item, must be unique and cannot benull。
  • Value(Value): the data corresponding to the key, which can benull。

Features:

  • Key-value pair storage: each key is unique and associated with a value.
  • Hash algorithm: locates data storage positions via the key's hash code, with an average time complexity of O(1) for lookup and insertion operations.
  • Dynamically adjust capacity: when the number of elements in the hash table exceeds capacity, the table dynamically expands and reallocates storage.
  • Unordered storage: the storage order of key-value pairs is independent of insertion order and is determined by the hash code.

Methods and properties of the Hashtable class

The table below listsHashtableSome commonly used ones of the classProperty:

Attribute NameTypeDescription
CountintGets the number of key-value pairs contained in the hash table.
IsReadOnlyboolIndicates whether the hash table is read-only.
IsFixedSizeboolIndicates whether the hash table has a fixed size.
IsSynchronizedboolIndicates whether the hash table is thread-safe.
KeysICollectionGets the collection of all keys in the hash table.
ValuesICollectionGets the collection of all values in the hash table.
SyncRootobjectGets an object that can be used to synchronize access to the hash table.

The table below listsHashtableSome commonly used ones of the classMethods:

Method NameReturn TypeDescription
Adding and removing
Add(object key, object value)voidAdds the specified key-value pair to the hash table.
Clear()voidClear the hash table.
Remove(object key)voidRemoves the key-value pair with the specified key.
Query and access
Contains(object key)boolDetermines whether the hash table contains the specified key.
ContainsKey(object key)boolDetermines whether the hash table contains the specified key (equivalent toContains)。
ContainsValue(object value)boolDetermines whether the hash table contains the specified value.
Copying and enumerating
CopyTo(Array array, int index)voidCopies the elements of the hash table to an array, starting at the specified index.
GetEnumerator()IDictionaryEnumeratorReturns an enumerator for the hash table, used to iterate through key-value pairs.

Example

The following example demonstrates the concept of the Hashtable:

Example

using System;
using System.Collections;

namespace CollectionsApplication
{
   class Program
   {
      static void Main(string[] args)
      {
         Hashtable ht = new Hashtable();


         ht.Add("001", "Zara Ali");
         ht.Add("002", "Abida Rehman");
         ht.Add("003", "Joe Holzner");
         ht.Add("004", "Mausam Benazir Nur");
         ht.Add("005", "M. Amlan");
         ht.Add("006", "M. Arif");
         ht.Add("007", "Ritesh Saikia");

         if (ht.ContainsValue("Nuha Ali"))
         {
            Console.WriteLine("This student name is already in the list");
         }
         else
         {
            ht.Add("008", "Nuha Ali");
         }
         // Get the collection of keys
         ICollection key = ht.Keys;

         foreach (string k in key)
         {
            Console.WriteLine(k + ": " + ht[k]);
         }
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it produces the following results:

007: Ritesh Saikia
004: Mausam Benazir Nur
005: M. Amlan
008: Nuha Ali
002: Abida Rehman
003: Joe Holzner
001: Zara Ali
006: M. Arif

Comparison with other collections

FeaturesHashtableDictionary<TKey, TValue>
Type SafetyNo (non-generic, storesobjecttype)Yes (generic, strongly typed constraints)
PerformanceSlower (requires boxing and unboxing operations)Faster (no boxing operations, generics directly support types)
Uniqueness of keysYesYes
Whether the value can benullYesYes
SortingNoneNone
Thread SafetyNot thread-safe by defaultNot thread-safe by default
  • HashtableIs an efficient key-value pair collection, suitable for scenarios requiring fast storage and retrieval of key-value pairs.
  • non-genericIts design makes it inferior to generic collections in terms of type safety and performance (such asDictionary<TKey, TValue>)。
  • In modern C# development,Dictionary<TKey, TValue>More commonly used, butHashtableIt is still suitable for simple applications or scenarios compatible with legacy code.

C# collections

other extensions