jro
jro

Reputation: 7480

Are Hashtable objects still useful?

Has the System.Collections.Hashtable object become obsolete?

With the implementation and refinements in generics from C# v2 and v3, it's been a long time since I've found a Hashtable more appropriate than a generic Dictionary. Literally, I can't recall the last time I used Hashtable.

Just wondering if anyone else has found a case where a Hashtable is still appropriate or preferred for implementation and the basis for that decision -- ease of use, performance, collection size, object type, etc.

UPDATE: was meaning to limit this question to C#.

Upvotes: 5

Views: 938

Answers (2)

JaredPar
JaredPar

Reputation: 755557

Hashtable's are still useful in the cases where you are dealing with a language, or version of a language, which does not support generic types.

EDIT

For C# 2.0 or higher, Hashtable is really only of useful for the following scenarios

  • You want to get the previous semantic of an IDictionary instance returning null vs. throwing in the case a key is not present in the table.
  • Dealing with a legacy API which exposes a Hashtable value

Hashstable is still useful as a general purpose map if you are stuck with C# 1.0 :)

Upvotes: 1

LBushkin
LBushkin

Reputation: 131796

Aside from the obvious case where you must use a Hashtable in an existing API that expects one (such as languages that don't yet support generic types). You also may need to use them if you need to access them from COM. I believe that Hashtable is COM visible, whereas Dictionary is not.

Other than that, you generally want to use Dictionary<> because it avoids boxing (a performance hit) and provides type safety.

Upvotes: 12

Related Questions