In most programming languages, dictionaries are preferred over hashtables. What are the reasons behind that?
According to what I see by using .NET Reflector:
[Serializable, ComVisible(true)]
public abstract class DictionaryBase : IDictionary, ICollection, IEnumerable
{
// Fields
private Hashtable hashtable;
// Methods
protected DictionaryBase();
public void Clear();
.
.
.
}
Take note of these lines
// Fields
private Hashtable hashtable;
So we can be sure that DictionaryBase uses a HashTable internally.
Notice that MSDN says: "Dictionary<(Of <(TKey, TValue>)>) class is implemented as a hash table", not "Dictionary<(Of <(TKey, TValue>)>) class is implemented as a HashTable"
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 .NET 1.0 Generics did not exist; this is where the HashTable and ArrayList originally began.
Dictionary
<<<>>> Hashtable
differences:
Synchronized()
methodKeyValuePair
<<<>>> Enumerated item: DictionaryEntry
Dictionary
/ Hashtable
similarities:
GetHashCode()
methodSimilar .NET collections (candidates to use instead of Dictionary and Hashtable):
ConcurrentDictionary
- thread safe (can be safely accessed from several threads concurrently)HybridDictionary
- optimized performance (for few items and also for many items)OrderedDictionary
- values can be accessed via int index (by order in which items were added)SortedDictionary
- items automatically sortedStringDictionary
- strongly typed and optimized for stringsSince .NET Framework 3.5 there is also a HashSet<T> which provides all the pros of the Dictionary<TKey, TValue> if you need only the keys and no values.
So if you use a Dictionary<MyType, object>
and always set the value to null
to simulate the type safe hash table you should maybe consider switching to the HashSet<T>.
One more difference that I can figure out is:
We can not use Dictionary<KT,VT> (generics) with web services. The reason is no web service standard supports the generics standard.
In .NET, the difference between Dictionary<,>
and HashTable
is primarily that the former is a generic type, so you get all the benefits of generics in terms of static type checking (and reduced boxing, but this isn't as big as people tend to think in terms of performance - there is a definite memory cost to boxing, though).