Difference between Hashtable and Dictionary in C#

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. Dictionary is defined under System.Collection.Genericsnamespace. It is dynamic in nature means the size of the dictionary is growing according to the need.

A Hashtable is a collection of key/value pairs that are arranged based on the hash code of the key. Or in other words, a Hashtable is used to create a collection which uses a hash table for storage. It is the non-generic type of collection which is defined in System.Collectionsnamespace. In Hashtable, key objects must be immutable as long as they are used as keys in the Hashtable.



Example:
// C# program to illustrate a hashtable
using System;
using System.Collections;
  
class GFG {
  
    // Main method
    static public void Main()
    {
  
        // Create a hashtable
        // Using Hashtable class
        Hashtable my_hashtable = new Hashtable();
  
        // Adding key/value pair in the hashtable
        // Using Add() method
        my_hashtable.Add("A1", "Welcome");
        my_hashtable.Add("A2", "to");
        my_hashtable.Add("A3", "Deepndani");
  
        foreach(DictionaryEntry element in my_hashtable)
        {
            Console.WriteLine("Key:- {0} and Value:- {1} ",
                               element.Key, element.Value);
        }



}
   
}




Example

// C# program to illustrate Dictionary
using System;
using System.Collections.Generic;
  
class Deepndani {
  
    // Main Method
    static public void Main()
    {
  
        // Creating a dictionary
        // using Dictionary<TKey, TValue> class
        Dictionary<string, string> My_dict = 
                    new Dictionary<string, string>();
  
        // Adding key/value pairs in the Dictionary
        // Using Add() method
        My_dict.Add("1", "Digital Marketing");
        My_dict.Add("2", "C++");
        My_dict.Add("3", "C#");
  
        foreach(KeyValuePair<string, string> element in My_dict)
        {
            Console.WriteLine("Key:- {0} and Value:- {1}"
                              element.Key, element.Value);
        }
    }
}

Output:

Key:- 1 and Value:- Digital Marketing
Key:- 2 and Value:- C++
Key:- 3 and Value:- C#







Comments