VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/difference-between-hashtable-and-dictionary-in-c-sharp/

⇱ C# Hashtable vs Dictionary - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C# Hashtable vs Dictionary

Last Updated : 11 Jul, 2025

In C# both Hashtable and Dictionary are used to store key-value pairs. Understanding the difference between Hashtable and Dictionary plays a very important role in choosing the right data structure for our C# applications. The main difference between Hashtable and Dictionary is:

  • Hashtable: This is an older, non-generic collection that treats everything as objects. This means it doesn’t enforce any type of safety, which could lead to errors at runtime if the wrong types are used.
  • Dictionary<TKey, TValue>: This is a modern, generic collection that works with specific types. This provides type safety, and better performance, and catches errors during compilation, making it a safer and faster option.

Note: Dictionary<TKey, TValue> is the preferred choice for most C# codes today because it’s more reliable and easier to work with.

Hashtable vs Dictionary

Features

Hashtable

Dictionary

Generic/Non-Generic

Hashtable is Non-generic.

Dictionary is generic.

Namespace

It is defined under System.Collections

It is defined under System.Collections.Generics

Type Safety

It does not enforce type safety.

It enforces type safety.

Boxing/Unboxing

It is slower because boxing/unboxing of data.

It is faster because there is no boxing/unboxing.

Accessing Missing Keys

It returns null for missing keys.

It returns KeyNotFoundException for missing keys.

Thread-Safety

It is thread-safe

It is not thread-safe

Performance

It is slower due to boxing/unboxing.

It is faster due to generics and no boxing/unboxing.

C# Hashtable

A Hashtable is a collection of key/value pairs that are arranged based on the hash code of the key. Or in other words, a Hashtable is used to create a collection which uses a hash table for storage. It is the non-generic type of collection which is defined in System.Collections namespace. In Hashtable, key objects must be immutable as long as they are used as keys in the Hashtable

Example: This example demonstrates how to create a Hashtable in C#, add key-value pairs, and print each key-value pair using a foreach loop.


Output
Key: 3 and Value: GeeksforGeeks 
Key: 2 and Value: to 
Key: 1 and Value: Welcome 

C# Dictionary

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. Dictionary is defined under System.Collection.Generics namespace. It is dynamic in nature means the size of the dictionary is growing according to the need

Example: This example demonstrates how to create a Dictionary in C#, add key-value pairs, and then print each key-value pair using a foreach loop.


Output
Key: 1 and Value: C
Key: 2 and Value: C++
Key: 3 and Value: C#
Comment

Explore