
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
How to Create a HashTable Collection in C#?
The HashTable is a non−generic collection in C#. It stores key-value pairs and is similar to a generic “Dictionary” collection. HashTable is defined in
System. Collections. namespace.
HashTable computes the hash code of each key and stores it in a different bucket internally. The hash code is then matched to the hash code of the specified key when the values are accessed. Thus the lookups are optimized by HashTable.
In this tutorial, we will see how we can create a HashTable collection in C#.
Hashtable Features
Before we jump to creating a HashTable, let us see some of the salient features of the HashTable collection in C#.
HashTable collection stores key−value pairs.
HashTable is a part of Systems. collections namespace in C# and implements the IDictionary interface. Elements of HashTable are stored as DictionaryEntry objects.
The HashTable keys must not be null and are unique. However, values can be null or duplicate.
Values in the HashTable can be accessed by using the key in the indexer just like the way we access array values.
Keys in HashTable are immutable objects. Each of these key objects provides a Hash function.
A typical Hashtable class implements the IDictionary, ICollection, ISerializable, IEnumerable, IDeserializationCallback, and ICloneable interfaces of C#.
Elements stored in HashTable can be of the same type or different types.
Keeping these salient features in mind, let us now discuss how to create a HashTable in C#.
How to Create a HashTable Collection in C#?
The HashTable class of C# provides 16 overloaded constructors to create a HashTable.
The following table shows the HashTable constructors that we will be using in this article.
Constructor | Description |
---|---|
Hashtable() | Initialization of new, an empty instances of the HashTable class with default initial capacity, hash code provider, comparator, and load factor. |
Hashtable(IDictionary) | Creates a new instance of the Hashtable class and initializes it with the contents of the specified dictionary. |
Note − To know more about the HashTable class in C#, read our article C#−HashTable Class.
Let’s see the steps we usually follow to create a HashTable collection in C#.
First, we include System. Collections namespace in our program
using System. Collections;
Next, we create a hashtable using the Hashtable class. For this, we use a default constructor.
Hashtable hashtable_name = new Hashtable();
Now we can use the “Add()” method to add elements to the HashTable.
So here, we can either initialize the entire HashTable while creating its instance or use Add() method to add elements to the HashTable one by one.
Example 1
The following program demonstrates the creation of HashTable in C#.
using System; using System. Collections; class MyHashTable { // Main Method static public void Main() { // Create hashtable using the default constructor Hashtable indianNumberSystem = new Hashtable(); //add a key/value pair using the Add() method indianNumberSystem.Add(1,"Ones"); indianNumberSystem.Add(10,"Tens"); indianNumberSystem.Add(100,"Hundred"); indianNumberSystem.Add(1000,"Thousand"); indianNumberSystem.Add(10000,"Ten Thousand"); indianNumberSystem.Add(100000,"Lac"); indianNumberSystem.Add(1000000,"Ten Lac"); indianNumberSystem.Add(10000000,"Crore"); //display HashTable contents Console.WriteLine("Key, Value pairs from Indian Number System:"); foreach(DictionaryEntry ele1 in indianNumberSystem){ Console.WriteLine("{0} ({1}) ", ele1.Key, ele1.Value); } } }
In the above program, we have defined a HashTable instance using the default constructor. Then we use the Add() method to add key/value pairs to the HashTable. Finally, the HashTable contents are printed one by one using a for-each loop.
Output
The above program generates the following output.
Key, Value pairs from Indian Number System: 100 (Hundred) 1000 (Thousand) 10 (Tens) 1000000 (Ten Lac) 100000 (Lac) 10000000 (Crore) 10000 (Ten Thousand) 1 (Ones)
The program displays a HashTable containing the place values of Indian Number System. Note that since this is a simple program to create a Hashtable and add contents to it, the output is not formatted.
Example 2
Let’s take another example of creating a HashTable in C#. The following program uses a different constructor for creating HashTable.
using System; using System.Collections; class MyHashTable { // Main Method static public void Main() { // Create hashtable without using Add method Hashtable my_hashtable1 = new Hashtable() {{"K1", "New York"}}; // Adding key/value pair in the hashtable using Add() method my_hashtable1.Add("K2", "Paris"); my_hashtable1.Add("K3", "London"); my_hashtable1.Add("K4", "Mumbai"); my_hashtable1.Add("K5", "Berlin"); Console.WriteLine("Key, Value pairs from my_hashtable1:"); foreach(DictionaryEntry ele1 in my_hashtable1){ Console.WriteLine("{0} and {1} ", ele1.Key, ele1.Value); } } }
As we can see in the above code, first we create a HashTable object with one key-value pair. Then we use add() method of the HashTable class to add elements to the HashTable. Finally, using a for-each loop, we iterate through the HashTable object to print each hashTable element (key-value pair).
Output
The above program produces the following output.
Key, Value pairs from my_hashtable1: K2 and Paris K1 and New York K3 and London K4 and Mumbai K5 and Berlin
In the above output, the key-value pairs are displayed in reverse alphabetical order of values. This is the default output of the HashTable since we haven’t provided any code to format the output. HashTable class provides various methods to organize/format the output which we will learn in subsequent tutorials.
In this tutorial, we have discussed how to create a HashTable collection in C#. HashTable is a non-generic collection of key-value pairs. The keys in HashTable are unique, non-null values. Values can be null and duplicated. We can create the HashTable in C# using the HashTable Class provided by Systems. Collections interface and modify it using various methods provided by this class.
- Related Articles
- How to Add Items to Hashtable Collection in C#
- How to Delete Item from Hashtable Collection in C#?
- How to create a shallow copy of Hashtable in C#?
- How to Get Value from HashTable Collection in C# using Specified Key
- How to create a new collection in MongoDB?
- C# Program to Check a HashTable collection is empty or not
- How to create and save a collection in Postman?
- C# Program to Get Key based on Value in Hashtable Collection
- How to create a MongoDB collection using Java?
- Create index in a MongoDB collection?
- Create a Read-Only Collection in Java
- How to create a collection correctly in MongoDB to avoid “ReferenceError: Not defined” error?
- Create a Stack from a collection in C#
- Check if a Hashtable is equal to another Hashtable in C#
- How to get keys from a HashTable in C#?
