I see many question/answers about how to convert a Hashtable to a Dictionary, but how can I convert a Dictionary to a Hashtable?
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.
Dictionary is NOT implemented as a HashTable, but it is implemented following the concept of a hash table. The implementation is unrelated to the HashTable class because of the use of Generics, although internally Microsoft could have used the same code and replaced the symbols of type Object with TKey and TValue. In .
Hashtable and Dictionary are collection of data structures to hold data as key-value pairs. Dictionary is generic type, hash table is not a generic type. The Hashtable is a weakly typed data structure, so you can add keys and values of any Object Type to the Hashtable.
Dictionary is a generic type and returns an error if you try to find a key which is not there. The Dictionary collection is faster than Hashtable because there is no boxing and unboxing.
The easiest way is using constructor of Hashtable:
var dictionary = new Dictionary<object, object>();
//... fill the dictionary
var hashtable = new Hashtable(dictionary);
Dictionary<int, string> dictionary = new Dictionary<int, string>
{
{1,"One"},
{2,"Two"}
};
Hashtable hashtable = new Hashtable(dictionary);
Try this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With