While doing simple thing I got confused about the difference between Hash table and Dictionary .Doing a simple program I got a clear picture about the difference.
Dictionary provides generic types <T Key, T Value> , which allows to create dictionary of any type. Where as Hash Table will store values in the form of object. So, while using a collection of primitive types such as integer, hash table will have additional cost of boxing and unboxing, where as dictionary is generic, it will not have additional cost of boxing and unboxing.
Please check the below example
Hashtable ht = new Hashtable();
ht.Add(1, "One");
ht.Add(2, "Two");
ht.Add(3, "Three");
foreach (DictionaryEntry de in ht)
{
int Key = (int)de.Key; //Casting
string value = de.Value.ToString(); //Casting
Console.WriteLine(Key + " " + value);
}
Console.ReadLine();
Dictionary<int, string> dt = new Dictionary<int, string>();
dt.Add(1, "One");
dt.Add(2, "Two");
dt.Add(3, "Three");
foreach (KeyValuePair<int, String> kv in dt)
{
Console.WriteLine(kv.Key + " " + kv.Value);
}
Console.ReadLine();
Dictionary provides generic types <T Key, T Value> , which allows to create dictionary of any type. Where as Hash Table will store values in the form of object. So, while using a collection of primitive types such as integer, hash table will have additional cost of boxing and unboxing, where as dictionary is generic, it will not have additional cost of boxing and unboxing.
Please check the below example
Hashtable ht = new Hashtable();
ht.Add(1, "One");
ht.Add(2, "Two");
ht.Add(3, "Three");
foreach (DictionaryEntry de in ht)
{
int Key = (int)de.Key; //Casting
string value = de.Value.ToString(); //Casting
Console.WriteLine(Key + " " + value);
}
Console.ReadLine();
Dictionary<int, string> dt = new Dictionary<int, string>();
dt.Add(1, "One");
dt.Add(2, "Two");
dt.Add(3, "Three");
foreach (KeyValuePair<int, String> kv in dt)
{
Console.WriteLine(kv.Key + " " + kv.Value);
}
Console.ReadLine();
No comments:
Post a Comment