Ccna final exam - java, php, javascript, ios, cshap all in one. This is a collaboratively edited question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
Sunday, May 20, 2012
Why Dictionary is preferred over hashtable in C#?
In most of programming languages, we preferred using a dictionary over a hashtable . What are the reasons behind it?
If you meant "why do we use the Dictionary class instead of the Hashtable class?", then it's an easy answer: Dictionary is a generic type, Hashtable is not. That means you get type safety with Dictionary, because you can't insert any random object into it, and you don't have to cast the values you take out.
Because Dictionary is a generic class ( Dictionary<TKey, TValue> ), so that accessing its content is type-safe (i.e. you do not need to cast from Object, as you do with a Hashtable).
Compare
var customers = new Dictionary<string, Customer>(); ... Customer customer = customers["Ali G"];
to
var customers = new Hashtable(); ... Customer customer = customers["Ali G"] as Customer;
FYI: In .Net Hashtable is thread safe for use by multiple reader threads and a single writing thread, while in Dictionary public static members are thread safe, but any instance members are not guaranteed to be thread safe.
We had to change all our Dictionaries back to Hashtable because of this.
Generic <<<>>> Non-Generic Needs own thread synchronization <<<>>> Offers thread safe version through Synchronized() method Enumerated item: KeyValuePair <<<>>> Enumerated item: DictionaryEntry Newer (> .NET 2.0) <<<>>> Older (since .NET 1.0) is in System.Collections.Generic <<<>>> is in System.Collections Request to non-existing key throws exception <<<>>> Request to non-existing key returns null
Dictionary / Hashtable similarities:
Both are internally hashtables == fast access to many-item data according to key Both need immutable and unique keys Keys of both need own GetHash() method
Similar .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 sorted StringDictionary - strongly typed and optimized for strings
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).
People are saying that a Dictionary is the same as a hash table.
This is not necessarily true. A hash table is an implementation of a dictionary. A typical one at that, and it may be the default one in .NET, but it's not by definition the only one.
You could equally well implement a dictionary with a linked list or a search tree, it just wouldn't be as efficient (for some metric of efficient).
The Hashtable is a loosely-typed data structure, so you can add keys and values of any type to the Hashtable. The Dictionary class is a type-safe Hashtable implementation, and the keys and values are strongly types. When creating a Dictionary instance, you must specify the data types for both the key and value.
one more difference that i can figure out is we can not use dictionary (generics) with web services the reason is no web service standard supports genrics standard.
This is not necessarily true. A hash table is an implementation of a dictionary. A typical one at that, and it may be the default one in .NET, but it's not by definition the only one.
I'm not sure that this is required by the ECMA standard, but the MSDN documentation very clearly calls it out as being implemented as a hashtable. They even provide the SortedList class for times when an alternative is more reasonable.
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 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.
FWIW, a Dictionary is a hash table.
ReplyDeleteIf you meant "why do we use the Dictionary class instead of the Hashtable class?", then it's an easy answer: Dictionary is a generic type, Hashtable is not. That means you get type safety with Dictionary, because you can't insert any random object into it, and you don't have to cast the values you take out.
Because Dictionary is a generic class ( Dictionary<TKey, TValue> ), so that accessing its content is type-safe (i.e. you do not need to cast from Object, as you do with a Hashtable).
ReplyDeleteCompare
var customers = new Dictionary<string, Customer>();
...
Customer customer = customers["Ali G"];
to
var customers = new Hashtable();
...
Customer customer = customers["Ali G"] as Customer;
FYI: In .Net Hashtable is thread safe for use by multiple reader threads and a single writing thread, while in Dictionary public static members are thread safe, but any instance members are not guaranteed to be thread safe.
ReplyDeleteWe had to change all our Dictionaries back to Hashtable because of this.
Dictionary <<<>>> Hashtable differences:
ReplyDeleteGeneric <<<>>> Non-Generic
Needs own thread synchronization <<<>>> Offers thread safe version through Synchronized() method
Enumerated item: KeyValuePair <<<>>> Enumerated item: DictionaryEntry
Newer (> .NET 2.0) <<<>>> Older (since .NET 1.0)
is in System.Collections.Generic <<<>>> is in System.Collections
Request to non-existing key throws exception <<<>>> Request to non-existing key returns null
Dictionary / Hashtable similarities:
Both are internally hashtables == fast access to many-item data according to key
Both need immutable and unique keys
Keys of both need own GetHash() method
Similar .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 sorted
StringDictionary - strongly typed and optimized for strings
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).
ReplyDeletePeople are saying that a Dictionary is the same as a hash table.
ReplyDeleteThis is not necessarily true. A hash table is an implementation of a dictionary. A typical one at that, and it may be the default one in .NET, but it's not by definition the only one.
You could equally well implement a dictionary with a linked list or a search tree, it just wouldn't be as efficient (for some metric of efficient).
The Hashtable is a loosely-typed data structure, so you can add keys and values of any type to the Hashtable. The Dictionary class is a type-safe Hashtable implementation, and the keys and values are strongly types. When creating a Dictionary instance, you must specify the data types for both the key and value.
ReplyDeleteone more difference that i can figure out is we can not use dictionary (generics) with web services the reason is no web service standard supports genrics standard.
ReplyDeleteThis is not necessarily true. A hash table is an implementation of a dictionary. A typical one at that, and it may be the default one in .NET, but it's not by definition the only one.
ReplyDeleteI'm not sure that this is required by the ECMA standard, but the MSDN documentation very clearly calls it out as being implemented as a hashtable. They even provide the SortedList class for times when an alternative is more reasonable.
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"
ReplyDeleteDictionary is NOT implemented as a HashTable, but 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.
According to what I see by using reflector:
ReplyDelete[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.