- 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# - Arithmetic Operators
- C# - Assignment Operators
- C# - Relational Operators
- C# - Logical Operators
- C# - Bitwise Operators
- C# - Miscellaneous Operators
- C# - Operators Precedence
- C# Conditional Statements
- C# - Decision Making
- C# - If
- C# - If Else
- C# - Nested If
- C# - Switch
- C# - Nested Switch
- C# - Switch Expressions
- C# Control Statements
- C# - Loops
- C# - For Loop
- C# - While Loop
- C# - Do While Loop
- C# - Nested Loops
- C# - Break
- C# - Continue
- C# - Foreach Loop
- C# - Goto Statement
- C# OOP & Data Handling
- 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# - LINQ
- C# - IEnumerable vs IEnumerator
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Tasks and Parallel Programming
- C# - Multithreading
- C# - Extension Methods
C# - Hashtable Class
Hashtable Class
The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. It uses the key to access the elements in the collection.
A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a key/value pair. The key is used to access the items in the collection.
Properties of Hashtable Class
The following table lists some of the commonly used properties of the Hashtable class −
| Sr.No. | Property & Description |
|---|---|
| 1 |
Count Gets the number of key-and-value pairs contained in the Hashtable. |
| 2 |
IsFixedSize Gets a value indicating whether the Hashtable has a fixed size. |
| 3 |
IsReadOnly Gets a value indicating whether the Hashtable is read-only. |
| 4 |
Item Gets or sets the value associated with the specified key. |
| 5 |
Keys Gets an ICollection containing the keys in the Hashtable. |
| 6 |
Values Gets an ICollection containing the values in the Hashtable. |
Methods Hashtable Class
The following table lists some of the commonly used methods of the Hashtable class −
| Sr.No. | Method & Description |
|---|---|
| 1 |
public virtual void Add(object key, object value); Adds an element with the specified key and value into the Hashtable. |
| 2 |
public virtual void Clear(); Removes all elements from the Hashtable. |
| 3 |
public virtual bool ContainsKey(object key); Determines whether the Hashtable contains a specific key. |
| 4 |
public virtual bool ContainsValue(object value); Determines whether the Hashtable contains a specific value. |
| 5 |
public virtual void Remove(object key); Removes the element with the specified key from the Hashtable. |
Creating a Hashtable
You can create an empty Hashtable by declaring it using the Hashtable class constructor as follows:p>
Hashtable hashtable = new Hashtable();
Initializing a Hashtable
Once Hashtable is created, you can initialize a it by adding key-value pairs as follows:
hashtable.Add("001", "Rahul Verma");
hashtable.Add("002", "Priya Desai");
hashtable.Add("003", "Vikram Singh");
Adding Elements to a Hashtable
You can add elements to a Hashtable using the Add() method or the indexer. The Add() method accepts the key and its value and pushes it into the Hashtable. In the case of the indexer, use the key as an index in the Hashtable and assign the values directly.
Using Add() Method
using System;
using System.Collections;
class Program {
static void Main(string[] args) {
Hashtable hashtable = new Hashtable();
hashtable.Add("A", "Amit Sharma");
hashtable.Add("B", "Bhavna Mehta");
hashtable.Add("C", "Chirag Patel");
foreach (DictionaryEntry entry in hashtable) {
Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
}
}
}
When the above code is compiled and executed, it produces the following result −
Key: C, Value: Chirag Patel Key: B, Value: Bhavna Mehta Key: A, Value: Amit Sharma
Using Indexer
using System;
using System.Collections;
class Program {
static void Main(string[] args) {
Hashtable hashtable = new Hashtable();
hashtable["D"] = "Deepika Rao";
hashtable["E"] = "Eshan Verma";
foreach (DictionaryEntry entry in hashtable) {
Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
}
}
}
When the above code is compiled and executed, it produces the following result −
Key: D, Value: Deepika Rao Key: E, Value: Eshan Verma
Accessing Elements from a Hashtable
You can access values from a Hashtable using their corresponding keys by placing the key, enclosed in double quotes, inside square brackets after the Hashtable name.
Example
The following example demonstrates how you can access an element from a Hashtable:
using System;
using System.Collections;
class Program {
static void Main(string[] args) {
Hashtable hashtable = new Hashtable();
hashtable.Add("X", "Xenia Gupta");
Console.WriteLine("Value at key 'X': " + hashtable["X"]);
}
}
When the above code is compiled and executed, it produces the following result −
Value at key 'X': Xenia Gupta
Iterating Through a Hashtable
You can iterate through a Hashtable using a foreach loop. Keys and values can be printed using the .Key and .Value properties.
Example
The following example demonstrates how you can iterate over a Hashtable's elements:
using System;
using System.Collections;
class Program {
static void Main(string[] args) {
Hashtable hashtable = new Hashtable();
hashtable.Add("101", "Rahul Mishra");
hashtable.Add("102", "Sneha Kapoor");
hashtable.Add("103", "Irfan Khan");
foreach (DictionaryEntry entry in hashtable) {
Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
}
}
}
When the above code is compiled and executed, it produces the following result −
Key: 101, Value: Rahul Mishra Key: 102, Value: Sneha Kapoor Key: 103, Value: Irfan Khan
Checking for Existence of Keys or Values
You can check whether a specific key or value exists in a Hashtable. Use the .ContainsKey() method to check for a key, and the .ContainsValue() method to check for a value.
Example: Check if a key exists
using System;
using System.Collections;
class Program {
static void Main(string[] args) {
Hashtable hashtable = new Hashtable();
hashtable.Add("P", "Pooja Rani");
if (hashtable.ContainsKey("P")) {
Console.WriteLine("Key 'P' exists in the hashtable.");
} else {
Console.WriteLine("Key 'P' does not exist.");
}
}
}
When the above code is compiled and executed, it produces the following result −
Key 'P' exists in the hashtable.
Example: Check if a value exists
using System;
using System.Collections;
class Program {
static void Main(string[] args) {
Hashtable hashtable = new Hashtable();
hashtable.Add("Q", "Qasim Ali");
if (hashtable.ContainsValue("Qasim Ali")) {
Console.WriteLine("Value 'Qasim Ali' exists in the hashtable.");
} else {
Console.WriteLine("Value does not exist.");
}
}
}
When the above code is compiled and executed, it produces the following result −
Value 'Qasim Ali' exists in the hashtable.
Removing Elements from a Hashtable
You can remove elements from a Hashtable using the Remove() method. The method accepts the key and remove the element (i.e., key and value both).
Example
The following example demonstrates how you can remove specific element from a Hashtable:
using System;
using System.Collections;
class Program {
static void Main(string[] args) {
Hashtable hashtable = new Hashtable();
hashtable.Add("K", "Kiran Joshi");
hashtable.Add("L", "Lakshmi Iyer");
hashtable.Remove("K");
foreach (DictionaryEntry entry in hashtable) {
Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
}
}
}
When the above code is compiled and executed, it produces the following result −
Key: L, Value: Lakshmi Iyer
Clearing a Hashtable
To remove all elements from a Hashtable, use the Clear() method.
Example
The following example demonstrating to clear a Hashtable:
using System;
using System.Collections;
class Program {
static void Main(string[] args) {
Hashtable hashtable = new Hashtable();
hashtable.Add("U", "Usha Devi");
hashtable.Add("V", "Vikram Yadav");
hashtable.Clear();
Console.WriteLine("Total items after clearing: " + hashtable.Count);
}
}
When the above code is compiled and executed, it produces the following result −
Total items after clearing: 0
Example: Hashtable Operations
The following example demonstrates the concept −
using System;
using System.Collections;
namespace CollectionsApplication {
class Program {
static void Main(string[] args) {
Hashtable ht = new Hashtable();
ht.Add("001", "Zara Ali");
ht.Add("002", "Abida Rehman");
ht.Add("003", "Joe Holzner");
ht.Add("004", "Mausam Benazir Nur");
ht.Add("005", "M. Amlan");
ht.Add("006", "M. Arif");
ht.Add("007", "Ritesh Saikia");
if (ht.ContainsValue("Nuha Ali")) {
Console.WriteLine("This student name is already in the list");
} else {
ht.Add("008", "Nuha Ali");
}
// Get a collection of the keys.
ICollection key = ht.Keys;
foreach (string k in key) {
Console.WriteLine(k + ": " + ht[k]);
}
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
001: Zara Ali 002: Abida Rehman 003: Joe Holzner 004: Mausam Benazir Nur 005: M. Amlan 006: M. Arif 007: Ritesh Saikia 008: Nuha Ali