C# Hash table and Dictionary Tutorial with Examples

C# Hash table and Dictionary Tutorial with Examples

Today, We want to share with you C# Hash table and Dictionary Tutorial with Examples.
In this post we will show you Why is Dictionary preferred over Hashtable?, hear for hashtable vs dictionary c# performance we will give you demo and example for implement.
In this post, we will learn about difference between hashtable and dictionary and arraylist in c# with an example.

Why is Dictionary preferred over Hashtable?

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

Now create Console Application in Visual Studio and write below lines of code in it.

Also Read :  Dynamically Add delete rows with JQuery Multiple datepicker

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.

C# Hashtable Example

using System;
using System.Collections;
namespace Pakainfo
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable _SiteList = new Hashtable();
            _SiteList.Add(1, "Pakainfo.com");
            _SiteList.Add(2, "Infinityknow.com");
            _SiteList.Add(3, "pakainfo.blogspot.com.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.
        }
    }
}

C# Dictionary Example

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

Read :

Also Read :  Great UNIX Commands Tutorial for Beginners

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about c# hashtable vs dictionary vs hashset.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.