Dictionary vs Hashtable in C#

In this article, we will discuss the difference between the Dictionary vs Hashtable in C# with examples. We will start with a brief introduction to data structures, coding implementations and then proceed to the comparison to each of them. Their usage and useful practical coding examples will help us to decide when and what should be used in our code.

The main difference between Dictionary and Hashtable is that dictionary is a generic type collection defined under System.Collection.Generics namespace which also stores data in the form of key/value pairs. Whereas, There is no requirement that the key and value in a hash table must be of the same data type; data of different data types can be stored as keys and values. Additionally, the type of the key and its value does not need to be specified. And the HashTable is the non-generic type of collection that is also used to store data in key/value pair and is defined in the System.Collections namespace.


Dictionary in C#:


A dictionary is a generic collection that can be used to store key/value pairs in C#. Dictionary operates quite similarly to non-generic hashtables. The distinction is that we must specify the type for both the keys and the values when building the generic dictionary object and the advantage of a Dictionary is, it is a generic type. The dictionary's size automatically increases when more entries are added to the generic Dictionary<TKey, TValue> collection due to its dynamic nature. The dictionary class is defined under the namespace System.Collections.Generic.


Dictionary<TKey, TValue>(): The Dictionary() constructor is used to create an instance of the Dictionary class that is empty and has the default initial capacity. Let's see how to use the Dictionary() in c# to create an instance of the Dictionary class.

Step 1:

The System.Collections.Generic namespace must be imported before the Dictionary class can be used in your program.

using System.Collections.Generic;

step 2:

Now the next step is, We  have to create an instance of the Dictionary<TKey, TValue> class using the Dictionary() constructor as follows:

Dictionary<string, string> dict_name = new Dictionary<string,string>();

This is the way to create a dictionary constructor. The class is defined in the code to create a dictionary with string types for both the keys and the values.

Given below is a sample example to understand the coding structure of dictionary implementations.

Example:

using System;

using System.Collections.Generic;

namespace MyDictionary

{

    internal class Program

    {

        static void Main(string[] args)

        {


            Dictionary<string, string> myDict = new Dictionary<string, string>();


            // Adding elements to dictionary using Add() method.


            myDict.Add("IND", "India");

            myDict.Add("USA", "united States of America");

            myDict.Add("UK", "United kingdom");

            myDict.Add("PAK", "Pakistan ");

            myDict.Add("SA", "South Africa");



// By using foreach loop we can access all the data by using ' KeyValuePair<> ' class.

            foreach(KeyValuePair<string, string> item in myDict)

            {

                Console.WriteLine("key is:" + item.Key + " Value is :" + item.Value);

            }



            Console.ReadLine();

        }

    }

}


Output:


key is:IND Value is: India

key is:USA Value is: united States of America

key is:UK Value is: United kingdom

key is:PAK Value is: Pakistan

key is:SA Value is: South Africa



Hashtable in C# :


A hashtable is a group of key/value pairs that are sorted according to the key’s hash code. Or, to put it another way, a collection that stores data in a hash table is created using a hashtable.  It is the non-generic type of collection that is defined in System.Collections namespace. As long as they are used as keys in the hashtable, key objects in the hashtables must be immutable.

The HashTable class offered by the .Net Framework includes all the features needed to construct a hashtable without the need for additional coding. A collection of all-purpose dictionaries is called a hashtable. The DictionaryEntry objects in the collection each have two properties: a key object and a value object. Key/Value pairs are what these are called. A hash code is produced automatically when items are added to a hash table. The key object serves as the sole method of accessing the values in the table. The collection's components should be regarded as being randomly organized because they are arranged according to the concealed hash code.



Methods of Hashtable:


Add(): Adds an item with a key and value into Hashtable.

Remove(): Removes the item with the specified key from the Hashtable.

Clear(): Removes all the items from the Hashtable.

Contains(): Checks whether the hashtable contains a specific key.

ContainsKey(): Checks whether the hashtable contains a specific key.


ContainsValue(): Checks whether the hashtable contains a specific key.


Now, let’s see how to create a hashtable in C#, Below is the syntax of Hashtable.

Step1:


The System.Collections namespace is where the Hashtable class resides. Therefore, using the "using" keyword, we must first include the System.Collections namespace in our program. The steps to do this are as follows.

using System.Collections;


Step2:

The next step is, we have to create an instance of the Hashtable class using the Hashtable constructor as follows.

Hashtable hashtable = new Hashtable();


Use the Add() function of the Hashtable class if you wish to add elements, such as a key/value pair, to the hashtable.


Add(object key, object? value): To add an element with the supplied key and value to the Hashtable, use the Add(object key, object? value) method. The element to be added's key is specified by the parameter key, and its value is specified by the parameter value in this case. The value can be empty.

Example:

hashtable.Add(“EId”,1001);
hashtable.
Add(“Name”, “James”);


Let’s Understand How to Create a Hashtable and Add Elements in C#:


Example:

using System.Collections;


class Program

{

    static void Main(string[] args)

    {

        //Creating Hashtable collection with default constructor

        Hashtable hashtable = new Hashtable();


        //Adding elements to the Hash table using key value pair

        hashtable.Add("Id", 12345); //Here key is id and value is 12345

        hashtable.Add("Name", "xyz"); //Here key is Name and value is xyz

        hashtable.Add("Salary", 8000);

        hashtable.Add("Location", "Kolkata");

        hashtable.Add("EmailID", "xyz@gmail.com");

                                            

        //Printing the keys and their values using foreach loop

        Console.WriteLine("Printing Hashtable using Foreach Loop");

        foreach (object item in hashtable.Keys)

        {

            Console.WriteLine(item + " : " + hashtable[item]);

        }

      



        Console.WriteLine("\nPrinting Hashtable using Keys");

        //I want to print the Location by using the Location key

        Console.WriteLine("Location : " + hashtable["Location"]);

        //I want to print the Email ID by using the EmailID key

        Console.WriteLine("Emaild ID : " + hashtable["EmailID"]);

        Console.ReadKey();

    }

}


Output:

Printing Hashtable using Foreach Loop

Name : xyz

Id : 12345

Location : Kolkata

EmailID : xyz@gmail.com

Salary : 8000


Printing Hashtable using Keys

Location : Kolkata

Emaild ID : xyz@gmail.com



Difference between Dictionary and Hashtable in C#:


      Dictionary

       Hashtable

 

The dictionary is included in the System.Collections.generic namespace.

 

 

Hashtable is included in the System.Collections namespace.

 

A dictionary is a generic collection. So it can store key-value pairs of specific data types.

 

Hashtable is a loosely typed (non-generic) collection, this means it stores key-value pairs of any data type.

 

 

A Dictionary is not thread-safe.

 

Hashtable is thread-safe.

 

The Dictionary collection is faster than Hashtable since there is no boxing and unboxing.

 

 

In Hashtable, the data retrieval is slower than in Dictionary due to boxing and unboxing.

 

A dictionary maintains the order of stored values.

 

Hashtable never maintains the order of stored values.

 

 

The dictionary will throw an exception if you try to find a key that doesn’t exist.

In the Dictionary, there is no need for boxing/unboxing.

 

 

Hashtable returns null when trying to find a key that does not exist. Values in Hashtable need boxing/unboxing.

 

 

A dictionary can support multiple readers concurrently, as long as the collection doesn’t modify.

 

 

Hashtable is thread-safe and can be used by multiple reader threads and a single writer thread.

 



Conclusion:


A dictionary is a generic collection that can be used to store key/value pairs in C#. Dictionary operates quite similarly to non-generic hashtables. The distinction is that we must specify the type for both the keys and the values when building the generic dictionary object and the advantage of a Dictionary is, it is a generic type. Whereas a hashtable is a group of key/value pairs that are sorted according to the key’s hash code. Or, to put it another way, a collection that stores data in a hash table is created using a hashtable.

hope you enjoyed reading this article and found it useful. Please share your thoughts and recommendations in the comment section below.


Share This Post

Linkedin
Fb Share
Twitter Share
Reddit Share

Support Me

Buy Me A Coffee