Why is Dictionary preferred over Hashtable in C#?

后端 未结 19 1259
长情又很酷
长情又很酷 2020-11-22 05:53

In most programming languages, dictionaries are preferred over hashtables. What are the reasons behind that?

19条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 06:29

    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);
            }
        }
    }
    

提交回复
热议问题