In C#, a Hashtable is a collection that stores data in the form of key-value pairs (key=>value), where both the key and the value can be any object.
Each item in a Hashtable has a key=>value pair. The key is used to access the item in the collection.
Hashtables organize and access data based on a hashing algorithm, providing efficient lookup, insertion, and deletion operations.
Hashtable is a non-generic collection located in the System.Collections namespace. If a generic version is needed, you can use Dictionary<TKey, TValue>.
Basic Structure:
- Key (
Key): Used to identify each data item. It must be unique and cannot benull. - Value (
Value): The data associated with the key. It can benull.
Characteristics:
- Key-Value Pair Storage: Each key is unique and associated with a value.
- Hashing Algorithm: Locates data storage positions using the key's hash code. The average time complexity for lookup and insertion operations is O(1).
- Dynamic Capacity Adjustment: When the number of elements exceeds the capacity, the table dynamically expands and reallocates storage.
- Unordered Storage: The storage order of key-value pairs is unrelated to the insertion order and is determined by the hash codes.
The following table lists some common properties of the Hashtable class:
| Property Name | Type | Description |
|---|---|---|
Count |
int |
Gets the number of key-value pairs contained in the Hashtable. |
IsReadOnly |
bool |
Indicates whether the Hashtable is read-only. |
IsFixedSize |
bool |
Indicates whether the Hashtable has a fixed size. |
IsSynchronized |
bool |
Indicates whether the Hashtable is thread-safe. |
Keys |
ICollection |
Gets a collection containing all the keys in the Hashtable. |
Values |
ICollection |
Gets a collection containing all the values in the Hashtable. |
SyncRoot |
object |
Gets an object that can be used to synchronize access to the Hashtable. |
The following table lists some common methods of the Hashtable class:
| Method Name | Return Type | Description |
|---|---|---|
| Addition and Removal | ||
Add(object key, object value) |
void |
Adds the specified key-value pair to the Hashtable. |
Clear() |
void |
Removes all elements from the Hashtable. |
Remove(object key) |
void |
Removes the element with the specified key. |
| Querying and Accessing | ||
Contains(object key) |
bool |
Determines whether the Hashtable contains a specific key. |
ContainsKey(object key) |
bool |
Determines whether the Hashtable contains a specific key (equivalent to Contains). |
ContainsValue(object value) |
bool |
Determines whether the Hashtable contains a specific value. |
| Copying and Enumeration | ||
CopyTo(Array array, int index) |
void |
Copies the Hashtable elements to an Array, starting at the specified index. |
GetEnumerator() |
IDictionaryEnumerator |
Returns an enumerator for the Hashtable, used to iterate through the key-value pairs. |
The following example demonstrates the concept of a 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);
}
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
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
| Feature | Hashtable |
Dictionary<TKey, TValue> |
|---|---|---|
| Type Safety | No (non-generic, stores object type) |
Yes (generic, strongly typed constraints) |
| Performance | Slower (requires boxing and unboxing operations) | Faster (no boxing, generic directly supports types) |
| Key Uniqueness | Yes | Yes |
Value Can Be null |
Yes | Yes |
| Ordering | None | None |
| Thread Safety | Not thread-safe by default | Not thread-safe by default |
Hashtableis an efficient key-value pair collection, suitable for scenarios requiring fast storage and retrieval of key-value pairs.- Its non-generic design makes it inferior to generic collections (like
Dictionary<TKey, TValue>) in terms of type safety and performance. - In modern C# development,
Dictionary<TKey, TValue>is more commonly used, butHashtableis still suitable for simple applications or scenarios requiring compatibility with legacy code.
YouTip