Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the generic version of a Hashtable?

Tags:

c#

.net

generics

I have been learning the basics of generics in .NET. However, I don't see the generic equivalent of Hashtable. Please share some sample C# code for creating generic hashtable classes.

like image 572
Charlie Avatar asked Apr 21 '09 14:04

Charlie


People also ask

Is C# Dictionary A Hashtable?

@BrianJ: Both HashTable (class) and Dictionary (class) are hash tables (concept), but a HashTable is not a Dictionary , nor is a Dictionary a HashTable .

Is Hashtable better than Dictionary?

Dictionary is faster than hashtable as dictionary is a generic strong type. Hashtable is slower as it takes object as data type which leads to boxing and unboxing.

What is Hashtable in C# with example?

The Hashtable is a non-generic collection that stores key-value pairs, similar to generic Dictionary<TKey, TValue> collection. It optimizes lookups by computing the hash code of each key and stores it in a different bucket internally and then matches the hash code of the specified key at the time of accessing values.


2 Answers

Dictionary<TKey, TValue>

Note that Dictionary is not a 100% drop in replacement for HashTable.

There is a slight difference in the way they handle NULLs. The dictionary will throw an exception if you try to reference a key that doesn't exist. The HashTable will just return null. The reason is that the value might be a value type, which cannot be null. In a Hashtable the value was always Object, so returning null was at least possible.

like image 112
Joel Coehoorn Avatar answered Sep 22 '22 14:09

Joel Coehoorn


The generic version of Hashtable class is System.Collections.Generic.Dictionary class.

Sample code:

Dictionary<int, string> numbers = new Dictionary<int, string>( );    numbers.Add(1, "one");    numbers.Add(2, "two");    // Display all key/value pairs in the Dictionary.    foreach (KeyValuePair<int, string> kvp in numbers)    {       Console.WriteLine("Key: " + kvp.Key + "\tValue: " + kvp.Value);    } 
like image 23
Gulzar Nazim Avatar answered Sep 21 '22 14:09

Gulzar Nazim