In most programming languages, dictionaries are preferred over hashtables. What are the reasons behind that?
Collections
& Generics
are useful for handling group of objects. In .NET, all the collections objects comes under the interface IEnumerable
, which in turn has ArrayList(Index-Value))
& HashTable(Key-Value)
. After .NET framework 2.0, ArrayList
& HashTable
were replaced with List
& Dictionary
. Now, the Arraylist
& HashTable
are no more used in nowadays projects.
Coming to the difference between HashTable
& Dictionary
, Dictionary
is generic where as Hastable
is not Generic. We can add any type of object to HashTable
, but while retrieving we need to cast it to the required type. So, it is not type safe. But to dictionary
, while declaring itself we can specify the type of key and value, so there is no need to cast while retrieving.
Let's look at an example:
HashTable
class HashTableProgram
{
static void Main(string[] args)
{
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);
}
}
}
Dictionary,
class DictionaryProgram
{
static void Main(string[] args)
{
Dictionary dt = new Dictionary();
dt.Add(1, "One");
dt.Add(2, "Two");
dt.Add(3, "Three");
foreach (KeyValuePair kv in dt)
{
Console.WriteLine(kv.Key + " " + kv.Value);
}
}
}