Monday, 20 April 2015

Hashtable and Dictionary

Hashtable and Dictionary are collection of data structures to hold data as key-value pairs.The Hashtable is a weakly typed data structure, so you can add keys and values of any Object Type to the Hashtable. The Dictionary class is a strongly types <T Key, T Value > and you must specify the data types for both the key and value.

Coming to difference between HashTable & Dictionary,Dictionary is generic whereas Hastable is not Generic.We can add any type of object to HashTable ,but while reteriving 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 & Value ,so no need to cast while retreiving.

Let me explain it with an Example. 

HashTable Program: 
    public 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 Example :
    class DictionaryProgram
    {
        static void Main(string[] args)
        {
            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);
            }
        }
    }



Dictionary
Trying to access an in existent key gives runtime error in Dictionary.
Dictionary is a generic type
Generic collections are a lot faster as there's no boxing/unboxing
Dictionary public static members are thread safe, but any instance members are not guaranteed to be thread safe.
Dictionary is preferred than Hash table

Hash table
Trying to access an in existent key gives null instead of error.
Hash table is a non-generic type
Hash table also have to box/unbox, which may have memory consumption as well as performance penalties.
Hash table is thread safe for use by multiple reader threads and a single writing thread
This is an older collection that is obsoleted by the Dictionary collection. Knowing how to use it is critical when maintaining older programs.

0 comments:

Post a Comment

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (9) Web Service (1) XMl (1)