Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Clear a Hashtable in C#
The Clear() method in C# is used to remove all key-value pairs from a Hashtable. This method provides an efficient way to empty the entire Hashtable in a single operation, resetting its count to zero while maintaining the original capacity.
Syntax
Following is the syntax for the The The
The output of the above code is − The output of the above code is − The Clear()
hashtable.Clear();
Parameters
Clear() method takes no parameters.Return Value
Clear() method does not return any value. It is a void method that modifies the Hashtable in place.Using Clear() to Empty a Hashtable
Example
using System;
using System.Collections;
public class Demo {
public static void Main() {
Hashtable h = new Hashtable();
h.Add(1, "Amit");
h.Add(2, "Sachin");
h.Add(3, "Rahul");
Console.WriteLine("Keys and Values list:");
foreach (var key in h.Keys) {
Console.WriteLine("Key = {0}, Value = {1}", key, h[key]);
}
Console.WriteLine("Count before Clear(): " + h.Count);
// clear all key value pairs
h.Clear();
Console.WriteLine("Count after Clear(): " + h.Count);
Console.WriteLine("The Hashtable is now empty.");
foreach (var key in h.Keys) {
Console.WriteLine("Key = {0}, Value = {1}", key, h[key]);
}
}
}
Keys and Values list:
Key = 3, Value = Rahul
Key = 2, Value = Sachin
Key = 1, Value = Amit
Count before Clear(): 3
Count after Clear(): 0
The Hashtable is now empty.
Clear() vs Creating New Hashtable
Example
using System;
using System.Collections;
public class ClearComparison {
public static void Main() {
// Method 1: Using Clear()
Hashtable h1 = new Hashtable();
h1.Add("A", 100);
h1.Add("B", 200);
Console.WriteLine("Before Clear() - Count: " + h1.Count);
h1.Clear();
Console.WriteLine("After Clear() - Count: " + h1.Count);
// Method 2: Creating new Hashtable
Hashtable h2 = new Hashtable();
h2.Add("X", 300);
h2.Add("Y", 400);
Console.WriteLine("Before reassignment - Count: " + h2.Count);
h2 = new Hashtable();
Console.WriteLine("After reassignment - Count: " + h2.Count);
}
}
Before Clear() - Count: 2
After Clear() - Count: 0
Before reassignment - Count: 2
After reassignment - Count: 0
Comparison
Method
Performance
Memory Usage
Use Case
Clear()
Fast - O(n)
Retains capacity
When reusing same Hashtable
New Hashtable
Fast - O(1)
Creates new object
When starting fresh
Conclusion
Clear() method efficiently removes all key-value pairs from a Hashtable, setting its count to zero while preserving the original capacity. This method is preferred when you need to reuse the same Hashtable object for new data.
