Clear a Hashtable in C#



Clear a Hashtable, using the Clear() method in C#.

The following is our Hashtable −

Hashtable h = new Hashtable(); h.Add(1, "Amit"); h.Add(2, "Sachin"); h.Add(3, "Rahul");

Use the clear method.

h.Clear();

If you will now try to display the Hashtable, nothing would get display since the Hashtable is empty.

Example

 Live Demo

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]);       }       // clear all key value pairs       Console.WriteLine("The Hashtable key and Value Pairs are empty now...");       h.Clear();       foreach (var key in h.Keys ) {          Console.WriteLine("Key = {0}, Value = {1}",key , h[key]);       }    } }

Output

Keys and Values list: Key = 3, Value = Rahul Key = 2, Value = Sachin Key = 1, Value = Amit The Hashtable key and Value Pairs are empty now...
Updated on: 2020-06-23T08:11:04+05:30

475 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements