What are Hashtable and Dictionary in C#?


Hashtable

//Create Hashtable
Hashtable objHash = new Hashtable();
objHash.Add("Hitesh", "1");
objHash.Add("Dev", "2");

//Get Value from Hashtable
int value1 = Convert.ToInt32(objHash["Hitesh1"]);
int value2 = Convert.ToInt32(objHash["Dev"]);
Console.WriteLine("{0},{1}", value1, value2);

  • it is not generic type because key and value are not declared with datatypes.
  • It is slower because it needs to convert value while getting data from hashtable.
  • Return null when requesting value does not exists.

Dictionary

//Create Dictionary
Dictionary<string, int >; objDic = new Dictionary < string, int > ()
{
    {"Hitesh",1},
    {"Dev",2}
};
//Get Value from dictionary
foreach (var d in objDic)
{
    Console.WriteLine("{0},{1}", d.Key, d.Value);
}

  • it is generic type because key and value are declared with datatypes.
  • It is fast because no need to convert value or no need for boxing and unboxing.
  • Return exception when requesting value does not exists.

One thought on “What are Hashtable and Dictionary in C#?

Comments are closed.