Table of Contents
Difference between Hashtable and Dictionary
Hey readers, till day you have read Insert data into Database table using SQLBulkCopy class in C#, Ping in C# , Call method after specific time interval C#, Insert Retrieve images from Database in asp.net LINQ TO SQL, Compare two objects in C# and datakey from GridView RowCommand. Today we will discuss regarding Difference between Hashtable and Dictionary with an example.
First of all we will try to understand what is Hashtable in C#?
Hashtable was introduced with Framework 1.1. Hashtable computes hash of each key which has been added.Each element is a key/value pair stored in a DictionaryEntry object. HashTable is thread safe for use by multiple reader threads and a single writing thread. Key must be non-null, but value could be null.
Hashtable Example:
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main(string[] args) { Hashtable hashtable = new Hashtable(); hashtable.Add("EmployeeName", "Pole"); hashtable.Add("EmployeeNo", 100); hashtable.Add("Position", "Developer"); hashtable.Add("JoiningDate", null); if (hashtable.ContainsKey("EmployeeName")) Console.WriteLine("Employee Name: "+Convert.ToString(hashtable["EmployeeName"])); Console.WriteLine("Joining Date: " + Convert.ToString(hashtable["JoiningDate"])); Console.ReadKey(); } } OUTPUT: Employee Name: Pole Joining Date:
What is Dictionary in C#?
Dictionary was introduced with Framework 2.0. Dictionary could be used when fast lookup is needed. Key and Value must not be null.
Dictionary Example:
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main(string[] args) { Dictionary<int, string> dictEmployees = new Dictionary<int, string>() { { 1, "Pole" }, { 2, "Adam" } }; foreach (KeyValuePair<int, string> pair in dictEmployees) Console.WriteLine("{0}, {1}", pair.Key, pair.Value); Console.ReadKey(); } } OUTPUT: 1, Pole 2, Adam
Difference between Hashtable and Dictionary
Hashtable |
Dictionary |
Slower than dictionary because it requires boxing and unboxing | Faster than a Hashtable because there is no boxing and unboxing |
Returns null if we try to find a key which does not exist | Returns error if we try to find a key which does not exist |
All the members in a Hashtable are thread safe | Only public static members are thread safe |
Hashtable is not a generic type | Dictionary is a generic type |
Key/value pair stored in a DictionaryEntry object | Key/value pair stored in a KeyValuePair object |