Why is Dictionary preferred over Hashtable in C#?

后端 未结 19 1433
长情又很酷
长情又很酷 2020-11-22 05:53

In most programming languages, dictionaries are preferred over hashtables. What are the reasons behind that?

19条回答
  •  自闭症患者
    2020-11-22 06:22

    Dictionary:

    • It returns/throws Exception if we try to find a key which does not exist.

    • It is faster than a Hashtable because there is no boxing and unboxing.

    • Only public static members are thread safe.

    • Dictionary is a generic type which means we can use it with any data type (When creating, must specify the data types for both keys and values).

      Example: Dictionary = new Dictionary();

    • Dictionay is a type-safe implementation of Hashtable, Keys and Values are strongly typed.

    Hashtable:

    • It returns null if we try to find a key which does not exist.

    • It is slower than dictionary because it requires boxing and unboxing.

    • All the members in a Hashtable are thread safe,

    • Hashtable is not a generic type,

    • Hashtable is loosely-typed data structure, we can add keys and values of any type.

提交回复
热议问题