Difference between HashTable and Dictionary C#

Hash table

  1. It returns null if we try to find a key which does not exist.
  2. It is slower than dictionary because it requires boxing and unboxing
  3. All the members in a Hashtable are thread safe,

Dictionary

  1. It returns error if we try to find a key which does not exist.
  2. It is faster than a Hashtable because there is no boxing and unboxing.
  3. Only public static members are thread safe.
  4. Dictionary is a generic type which means we can use it with any data type.

Sample Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace HashvsDictionary
{
class Program
{
static Hashtable hashtable { get; set; }

static Dictionary<string, string> dictionary { get; set; }

static void Main(string[] args)
{
Program.hashtable = new Hashtable();
//You can add object type key values to HashTable so while retrieving need to unbox the original datatype
hashtable.Add(“1012”, “Thiru”);
hashtable.Add(“1013”, “Raj”);

Program.dictionary = new Dictionary<string, string>();
dictionary.Add(“1012”, “Thiru”);
dictionary.Add(“1013”, “Raj”);

Console.WriteLine(string.Format(” Key present :{0} Key Not present:{1}”, hashtable[“1013”], hashtable[“1016”]));

//It will throw error since key is not present
Console.WriteLine(string.Format(” Key present :{0} Key Not present:{1}”, dictionary[“1013”], dictionary[“1016”])); ;
Console.ReadLine();

}
}
}