SoFunction
Updated on 2025-03-07

The difference between Hashtable and Dictionary in C#

Hashtable and Dictionary are both data structures used in C# to store key-value pairs.

Hashtable

Using Hashtable requires the introduction of a namespace. The key/value pairs of key/value in Hashtable are all object types, so Hashtable can support any type of key/value key/value pairs. Each object in Hashtable is a key/value pair stored in the DictionaryEntry object.

Common properties

property describe
Count Get the number of key-value pairs contained in a Hashtable
Keys Get a collection of all keys in a Hashtable
Values Get a collection of all values ​​in a Hashtable

Common methods

method describe
public virtual void Add(object key, object value); Add an element with the specified key and value to the Hashtable
public virtual bool ContainsKey(object key); Determine whether the Hashtable contains the specified key
public virtual bool ContainsValue(object value); Determine whether the Hashtable contains the specified value
public virtual void Remove(object key); Remove elements of the specified key from a Hashtable
public virtual void Clear(); Remove all elements from Hashtable

Note: Since the IDictionary interface is the base interface of a non-generic collection of key/value pairs, and each element is a key/value pair and is stored in a DictionaryEntry object, the element type is neither the type of the key nor the type of the value, but the DictionaryEntry type. (Leave a pit, I didn't understand what it is)

Hashtable ht = new Hashtable();

(1, true);
(2, "FALSE");

("Currently contains the number of key-value pairs:{0}", );//Output: 2
("---- Find key-value pairs by key ----");
foreach (var key in )
{
    ("{0} - {1}", key, ht[key]);//Output: 2-"FALSE" 1-True}

("---- Collection of added values ​​----");
foreach (var value in )
{
    ("{0}", value);//Output: FALSE True}

if ((1))
{
    ("Hashtable contains key 1.");//Output}

if((true))
{
    ("Hashtable contains the value true.");//Output}

(1);
("---- After removing key 1 ----");
foreach(DictionaryEntry de in ht)
{
    ("{0} - {1}", , );//Output: 2 - FALSE}


();
("---- After removing all ----");
foreach (DictionaryEntry de in ht)
{
    ("{0} ------- {1}", , );//No output}

();

Dictionary

Dictionary<TKey, TValue> is included in the namespace. Dictionary<TKey, TValue> can supportSpecifyany type of key/value key-value pair. Therefore, the Dictionary<TKey, TValue> object can only add key/value key-value pairs of the specified type. Each object in Dictionary<TKey, TValue> is a key-value pair stored in the KeyValuePair<TKey, TValue> object.

Common properties

property describe
Count Get the number of key-value pairs contained in Dictionary<TKey, TValue>
Item Get a key value pair in Dictionary<TKey, TValue>
Keys Get a collection of all keys in Dictionary<TKey, TValue>
Values Get a collection of all values ​​in Dictionary<TKey, TValue>

Common methods

method describe
public void Add(TKey key, TValue value); Add the specified key and value to the dictionary
public bool ContainsKey(TKey key); Determine whether Dictionary<TKey, TValue> contains the specified key
public bool ContainsValue(TValue value); Determine whether Dictionary<TKey, TValue> contains the specified value
public bool Remove(TKey key); Remove from Dictionary<TKey, TValue>SpecifyElements of keys
public void Clear(); Remove from Dictionary<TKey, TValue>allKey value pairs
Dictionary&lt;int, string&gt; dc = new Dictionary&lt;int, string&gt;();

(21002121, "Zhang San");
(21002122, "Li Si");

("Number of key-value pairs in the dictionary:{0}", );//Output: 2
("---- Key-value pair after addition ----");
foreach (var item in dc)
{
    ("{0} - {1}", , );//Output: 21002121 - Zhang San 21002122 - Li Si}

("---- Find key-value pairs by key ----");
foreach (var key in )
{
    ("{0} - {1}", key, dc[key]);//Output: 21002121 - Zhang San 21002122 - Li Si}

("---- Collection of added values ​​----");
foreach (var value in )
{
    ("{0}", value);//Zhang San Li Si}

if((21002121))
{
    ("Dictionary contains key 21002121.");//Output}

if(("Li Si"))
{
    ("Dictionary contains the value Li Si.");//Output}

(21002121);

("---- After removing key 21002121 ----");
foreach (KeyValuePair&lt;int, string&gt; kp in dc)
{
    ("{0} - {1}", , );//Output: 21002122 - Li Si}

();
("---- After removing all ----");
foreach (KeyValuePair&lt;int, string&gt; kp in dc)
{
    ("{0} ----- {1}", , );//No output}


();

Comparison of the time between Hashtable and Dictionary insertion methods

Dictionary&lt;int, int&gt; dc = new Dictionary&lt;int, int&gt;();
Hashtable ht = new Hashtable();

int count = 10000000;//The number of insertions is 10 millionStopwatch sw = new Stopwatch();
();//Timefor(int i = 0; i &lt; count; i++)
{
    (i, i);
}
();
("dictionaryDictionary&lt;TKey, TValue&gt;time consuming(millisecond):" + );//Output: 388
();
for (int i = 0; i &lt; count; i++)
{
    (i, i);
}
();
("Hash tableHashtabletime consuming(millisecond):" + );//Output: 2497();

Note: The time consumed is not unique, computers with average performance recommend reducing the number of inserts

the difference

1. Implementation method:

Hashtable is implemented based on hash tables, while Dictionary is implemented based on generics.

2. Type safety:

Hashtable is non-generic and can store keys and values ​​of any type, while Dictionary is generic and can specify the types of keys and values ​​and perform type checks at compile time to provide better type safety.

3. Performance:

Since Hashtabl is non-generic, it requires boxing and unboxing operations when storing and retrieving data, which will cause certain performance losses. Dictionary is generic and does not require boxing and unboxing operations, so it is usually better in performance than Hashtable.

4. Nullable keys and values:

Hashtable allows storing null keys and null values, while Dictionary does not allow storing null keys and null values.

5. Iteration order:

Key-value pairs in Hashtable are out of order, while key-value pairs in Dictionary are sorted in insertion order.

Summarize:

  • Dictionary is recommended if you need a key-value pair set that is type-safe, has good performance and does not need to store null keys and null values.
  • If you need a key and value that can store any type, and you don't care about performance and type safety, you can use Hashtable.

This is the end of this article about the difference between Hashtable and Dictionary in C#. For more related content on C#, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!