Why is Dictionary preferred over Hashtable?

In this post, we will learn about Why is Dictionary preferred over Hashtable? with an example.

Description:

In my previous posts I have explained various topics like Introduction to BackboneJS, Bind an enumeration to combobox in WinForm, jQuery is undefined error: Common mistake every developer should avoid, 15 Powerful jQuery Tips and Tricks for Developers and Designer.



Now in this post, I will explain Why is Dictionary preferred over Hashtable? with appropriate example. Dictionary is generic whereas Hashtable 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 the dictionary, while declaring we can specify the type of key and value, so there will be no need to cast while retrieving.

Hashtable Example

using System;
using System.Collections;
namespace DotNetK
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable _SiteList = new Hashtable();
            _SiteList.Add(1, "DotNetK.com");
            _SiteList.Add(2, "Live24u.com");
            _SiteList.Add(3, "W3school.com");
            foreach (DictionaryEntry de in _SiteList)
            {
                int Key = (int)de.Key; //Casting
                string value = de.Value.ToString(); //Casting
                Console.WriteLine(Key + " " + value);
            }          

            Console.ReadKey(); // To hold the console screen.
        }
    }
}

Dictionary Example

using System;
using System.Collections;
using System.Collections.Generic;
namespace DotNetK
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> _SiteList = new Dictionary<int, string>();
            _SiteList.Add(1, "DotNetK.com");
            _SiteList.Add(2, "Live24u.comm");
            _SiteList.Add(3, "W3school.com");
            foreach (KeyValuePair<int, String> kv in _SiteList)
            {
                Console.WriteLine(kv.Key + " " + kv.Value);
            }
            Console.ReadKey(); // To hold the console screen.
        }
    }
}




Read :

Summary

You can also read about ASP.NET, C#.Net, JQUERY, AJAX, JavaScript
I hope you get an idea about Why is Dictionary preferred over Hashtable?.
I would like to have feedback on my blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you liked this post, don’t forget to share this.

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *
Email *
Website