DICTIONARY VS HASHTABLE in C# REAL TIME EXAMPLES

Differences Between Hashtable and Dictionary

1. Hashtable is threadsafe and while Dictionary is not.

// Creates a synchronized wrapper around the Hashtable.

  Ex:Hashtable myhashtable = Hashtable.Synchronized(hash);
The Synchronized method is thread safe for multiple readers and writers. Furthermore, the synchronized wrapper ensures that there is only one writer writing at a time.



2. Dictionary is types means that the values need not to boxing while Hashtable
    values  need to be boxed or unboxed because it stored the  values and keys as
    objects.        
3. When you try to get the value of key which does not exists in the collection, the
    dictionary throws an exception of 'KeyNotFoundException' while hashtable returns
    null value.
4. When using large collection of key value pairs hashtable would be considered more
    efficient than dictionary.
5. When we retrieve the record in collection the hashtable does not maintain the order
    of entries while dictionary maintains the order of entries by which entries were added.
6. Dictionary relies on chaining whereas Hashtable relies on rehashing.

7.Dictionary is a strongly typed generic collection while hashtable collection takes a object datatype

 

 

 

 

 

 

 

 

 

var colors = new Dictionary<String, int>();

 

colors.Add("1", 1);

colors.Add("2", 1);

foreach (KeyValuePair<string, int> kvp in colors)

{

string tt = kvp.Key;

int tt1 = kvp.Value;

}

 

foreach (string key in colors.Keys)

{

Console.Write(key);

}

if (colors.ContainsKey("1"))

{

colors.Remove("6");

}

/////////////Hash table

 

var hash = new Hashtable();

hash.Add(7, 9);

hash.Add(8, 9);

 

// Creates a synchronized wrapper around the Hashtable.Hashtable mySyncdHT = Hashtable.Synchronized(hash);
//Returns a Synchronized (Thread safe) Wrapper on the Hashtable my = Hashtable.Synchronized(hash);

if (hash.ContainsKey(7))

{

hash.Remove(11);

}

 

foreach (DictionaryEntry Entry in hash)

{

string tt = Entry.Key.ToString();

 

Console.Write(hash.Keys);

}

Comments

Post a Comment