Difference between hashtable and dictionary in C#
In this article, we will discuss the difference between Hashtable and Dictionary in C#. But before discussing their differences, we must know about the Hashtable and Dictionary.
Key-value pairs can be stored in C# using either Dictionary or Hashtable data structures, but they have different features and implementations.
Hash Table:
- The System includes a collection class called Hashtable.Namespace for collections.
- Key-value pairs are kept as objects in this non-generic collection.
- Hashtable is based on the hash table data structure, in which elements are kept in buckets according to the key's hash code.
- It provides a quick method of using keys to access elements.
- Null can be a key and a value in a Hashtable.
- We can store any kind of key and value because it is not type-safe.
- Hashtable read operations are thread-safe, but write operations are not. When using a Hashtable in a multi-threaded environment, write operations must be manually synchronized.
- A Hashtable's enumeration may not always occur in the same sequence that the elements were added.
Dictionary:
- A general collection class in the System is called Dictionary.Collections.generic namespace.
- Dictionary was added to the .NET Framework 2.0 and requires explicit typing for both keys and values.
- Similar to Hashtable, it is based on a hash table data structure.
- As dictionaries offer type safety, we can designate the kinds of keys and values that they can store.
- It lets elements be retrieved more quickly with keys.
- Null values can be stored in dictionaries, but null keys cannot.
- There is no thread safety for any operation in Dictionary, unlike Hashtable. The ConcurrentDictionary class or manual access synchronization should be used if thread safety is needed.
- The sequence in which elements are added to a dictionary is not always guaranteed to be maintained when enumerated.
Main Difference between the Hashtable and Dictionary in C#.
There are several main differences between the Hashtable and Dictionary in C#. Some main differences between these methods are as follows:
Hashtable | Dictionary |
A non-generic collection is called a hashtable. | A dictionary is an all-purpose compilation. |
The term "Hashtable" is defined in System.namespace for collections. | System defines dictionary.Collections.general namespace. |
We can store key/value pairs of the same type or different types in a Hashtable. | We can store key-value pairs of the same type in dictionaries. |
It is not necessary to specify the type of key or value in a Hashtable. | We have to indicate the kind of key and value in Dictionary. |
Boxing and unpacking causes the data retrieval to be slower than Dictionary. | Without any packaging or unpacking, the data retrieval is quicker than with a Hashtable. |
When attempting to access a key in a Hashtable that is not present, null values will be returned. | We will receive an error in Dictionary if we attempt to access a key that is not included in the specified Dictionary. |
Thread safety is maintained. | However, only for public static members, it is likewise thread safe. |
The stored values are not kept in order by it. | The stored values are always kept in the same order. |
Example:
Let us take an example to illustrate the Hashtable and Dictionary in C#.
using System;
using System.Collections; // Required for Hashtable
using System.Collections.Generic; // Required for Dictionary
class Program
{
static void Main(string[] args)
{
// Hashtable example
Hashtable hashtable = new Hashtable();
hashtable.Add("key1", "value1");
hashtable.Add("key2", "value2");
hashtable.Add("key3", "value3");
Console.WriteLine("Hashtable Example:");
foreach (DictionaryEntry entry in hashtable)
{
Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
}
// Dictionary example
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("key1", "value1");
dictionary.Add("key2", "value2");
dictionary.Add("key3", "value3");
Console.WriteLine("\nDictionary Example:");
foreach (KeyValuePair<string, string> entry in dictionary)
{
Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
}
Console.ReadLine();
}
}
Output:
Hashtable Example:Key: key1, Value: value1Key: key3,
Value: value3Key: key2, Value: value2
Dictionary Example:Key: key1, Value: value1Key: key2,
Value: value2Key: key3, Value: value3
Explanation:
In this example, this C# code shows how to initialize, add key-value pairs, and iterate over the elements of a hashtable and dictionary. We can see that Dictionary uses generics to provide type safety and more readable syntax.
Example 2:
Let us take another example to illustrate the Hashtable and Dictionary in C#.
using System;
using System.Collections; // Required for Hashtable
using System.Collections.Generic; // Required for Dictionary
class Program
{
static void Main(string[] args)
{
// Hashtable example
Hashtable hashtable = new Hashtable();
hashtable.Add("key1", "value1");
hashtable.Add("key2", "value2");
hashtable.Add("key3", "value3");
Console.WriteLine("Hashtable Example:");
PrintValue(hashtable, "key2");
// Remove a key from Hashtable
RemoveKey(hashtable, "key1");
// Try accessing a non-existent key
PrintValue(hashtable, "key1");
// Dictionary example
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("key1", "value1");
dictionary.Add("key2", "value2");
dictionary.Add("key3", "value3");
Console.WriteLine("\nDictionary Example:");
PrintValue(dictionary, "key2");
// Remove a key from Dictionary
RemoveKey(dictionary, "key1");
// Try accessing a non-existent key
PrintValue(dictionary, "key1");
Console.ReadLine();
}
static void PrintValue(IDictionary collection, string key)
{
try
{
Console.WriteLine($"Value for key '{key}': {collection[key]}");
}
catch (Exception ex)
{
Console.WriteLine($"Error accessing key '{key}': {ex.Message}");
}
}
static void RemoveKey(IDictionary collection, string key)
{
try
{
collection.Remove(key);
Console.WriteLine($"Key '{key}' removed successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"Error removing key '{key}': {ex.Message}");
}
}
}
Output:
Hashtable Example:
Value for key 'key2': value2
Key 'key1' removed successfully.
Value for key 'key1':
Dictionary Example:
Value for key 'key2': value2
Key 'key1' removed successfully.
Value for key 'key1':