C# HashTable

In c#, Hashtable is used to store a collection of key/value pairs of different data types, and those are organized based on the hash code of the key.

 

Generally, the hashtable object will contain buckets to store elements of the collection. Here, the bucket is a virtual subgroup of elements within the hashtable, and each bucket is associated with a hash code, which is generated based on the key of an element.

 

In c#, the hashtable is same as a dictionary object, but the only difference is the dictionary object is used to store a key-value pair of the same data type elements.

 

When compared with dictionary objects, the hashtable will provide a lower performance because the hashtable elements are of object type, so the boxing and unboxing process will occur when we store or retrieve values from the hashtable.

C# HashTable Declaration

In c#, hashtable is a non-generic type of collection to store a key/value pair elements of different data types, and it is provided by System.Collections namespace.

 

As discussed, the collection is a class, so to define a hashtable, you need to declare an instance of the hashtable class before we perform any operations like add, delete, etc. as shown below.

 

Hashtable htbl = new Hashtable();

If you observe the above hashtable declaration, we created a new hashtable (hshtbl) with an instance of hashtable class without specifying any size.

C# HashTable Properties

The following are some of the commonly used properties of hashtable in the c# programming language.

 

PropertyDescription
Count It is used to get the number of key/value pair elements in the hashtable.
IsFixedSize It is used to get a value to indicate whether the hashtable has a fixed size or not.
IsReadOnly It is used to get a value to indicate whether the hashtable is read-only or not.
Item It is used to get or set the value associated with the specified key.
IsSynchronized It is used to get a value to indicate whether access to the hashtable is synchronized (thread-safe) or not.
Keys It is used to get the collection of keys in the hashtable.
Values It is used to get the collection of values in the hashtable.

C# HashTable Methods

The following are some of the commonly used methods of hashtable to perform operations like add, delete, etc., on elements of hashtable in c# programming language.

 

MethodDescription
Add It is used to add an element with a specified key and value in a hashtable.
Clear It will remove all the elements from the hashtable.
Clone It will create a shallow copy of the hashtable.
Contains It is useful to determine whether the hashtable contains a specific key or not.
ContainsKey It is useful to determine whether the hashtable contains a specific key or not.
ContainsValue It is useful to determine whether the hashtable contains a specific value or not.
Remove It is useful to remove an element with a specified key from the hashtable.
GetHash It is useful to get the hash code for the specified key.

C# Add Elements to HashTable

In c#, while adding elements to the hashtable, you need to make sure that there will not be any duplicate keys because the hashtable will allow us to store duplicate values, but keys must be unique to identify the values in the hashtable.

 

In the hashtable, we can add key/value pair elements of different data types. Following is the example of adding elements to the hashtable in c#.

 

using System;
using System.Collections;

namespace Tutlane
{
    class Program
    {
       static void Main(string[] args)
       {
           Hashtable htbl = new Hashtable();
           htbl.Add("msg", "Welcome");
           htbl.Add("site", "Tutlane");
           htbl.Add(1, 20.5);
           htbl.Add(2, null);
           // Another way to add elements. If the key does not exist, then that key adds a new key/value pair.
           htbl[3] = "Tutorials";
           // Add method will throw an exception if the key already exists in the hashtable
           try
           {
               htbl.Add(2, 100);
           }
           catch
           {
               Console.WriteLine("An element with Key = '2' already exists.");
           }
           Console.WriteLine("*********HashTable Elements********");
           // It will return elements as KeyValuePair objects.
           foreach (DictionaryEntry item in htbl)
           {
               Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
           }
           Console.ReadLine();
       }
    }
}

If you observe the above example, we created a new hashtable (htbl) and added different data type elements (key/value) to the hashtable (htbl) in different ways. As discussed, Add method will throw an exception if we try to add a key (2) that is already existing to handle that exception; we used a try-catch block.

 

When you execute the above c# program, we will get the result below.

 

C# Add Elements to HashTable Example Result

 

If you observe the above result, we got an exception when we tried to add a key (2) that is already existing and added a key (3) that is not existing in the hashtable.

 

In c#, we can also assign key/value pairs to hashtable at the time of initialization as shown below.

 

Hashtable htbl = new Hashtable(){
                     {"msg", "Welcome"},
                     {"site", "Tutlane"},
                     {1, 20.5},
                     {2, null}
                 };

C# Access HashTable Elements

In c#, we have different ways to access hashtable elements, i.e., either using keys or by iterating through a hashtable using a foreach loop.

 

Following is an example of accessing hashtable elements in different ways.

 

using System;
using System.Collections;

namespace Tutlane
{
    class Program
    {
       static void Main(string[] args)
       {
           Hashtable htbl = new Hashtable();
           htbl.Add("msg", "Welcome");
           htbl.Add("site", "Tutlane");
           htbl.Add(1, 20.5f);
           htbl.Add(2, 10);
           string msg = (string)htbl["msg"];
           float num = (float)htbl[1];
           Console.WriteLine("*********Access Elements with Keys********");
           Console.WriteLine("Value at Key 'msg': " + msg);
           Console.WriteLine("Value at Key '1': " + num);
           Console.WriteLine("*********Access Elements with Foreach Loop********");
           foreach (DictionaryEntry item in htbl)
           {
               Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
           }
           Console.WriteLine("*********HashTable Keys********");
           foreach (var item in htbl.Keys)
           {
               Console.WriteLine("Key = {0}", item);
           }
           Console.WriteLine("*********HashTable Values********");
           foreach (var item in htbl.Values)
           {
               Console.WriteLine("Value = {0}", item);
           }
           Console.ReadLine();
       }
    }
}

If you observe the above example, we access hashtable elements in different ways by using keys, foreach loop, and available properties (Keys, Values) based on our requirements.

 

When you execute the above c# program, we will get the result below.

 

C# Access HashTable Elements Example Result

C# Remove Elements from HashTable

In c#, you can delete elements from the hashtable by using the Remove() method. Following is the example of deleting elements from the hashtable in the c# programming language.

 

using System;
using System.Collections;

namespace Tutlane
{
    class Program
    {
       static void Main(string[] args)
       {
          Hashtable htbl = new Hashtable();
          htbl.Add("msg", "Welcome");
          htbl.Add("site", "Tutlane");
          htbl.Add(1, 20.5f);
          htbl.Add(2, 10);
          htbl.Add(3, 100);
          // Removing hashtable elements with keys
          htbl.Remove(1);
          htbl.Remove("msg");
          Console.WriteLine("*********HashTable Elements********");
          foreach (DictionaryEntry item in htbl)
          {
             Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
          }
          Console.ReadLine();
       }
    }
}

If you observe the above example, we used a Remove() method to delete a particular value of the element from the hashtable using keys.

 

When you execute the above c# program, we will get the result below.

 

C# Remove HashTable Elements Example Result

 

If you want to remove all the elements from a hashtable, then use the Clear() method.

C# HashTable Check If Element Exists

By using Contains(), ContainsKey(), and ContainsValue() methods, we can check whether the specified element exists in the hashtable or not. In case it exists, these methods will return true otherwise false.

 

Following is the example of using Contains(), ContainsKey(), and ContainsValue() methods to check for an item that exists in a hashtable or not in c#.

 

using System;
using System.Collections;

namespace Tutlane
{
    class Program
    {
       static void Main(string[] args)
       {
           Hashtable htbl = new Hashtable();
           htbl.Add("msg", "Welcome");
           htbl.Add("site", "Tutlane");
           htbl.Add(1, 20.5f);
           htbl.Add(2, 10);
           htbl.Add(3, 100);
           Console.WriteLine("Contains Key 4: {0}", htbl.Contains(4));
           Console.WriteLine("Contains Key 2: {0}", htbl.ContainsKey(2));
           Console.WriteLine("Contains Value 'Tutlane': {0}", htbl.ContainsValue("Tutlane"));
           Console.ReadLine();
       }
    }
}

If you observe the above example, we used Contains(), ContainsKey(), and ContainsValue() methods to check for particular keys and values that exist in a hashtable (htbl) or not.

 

When you execute the above c# program, we will get the result below.

 

C# Check Elements Exists in Hashtable or Not Example Result

C# HashTable Overview

The following are the important points that need to remember about hashtable in c#.

 

  • Hashtable is used to store a collection of key/value pairs of different data types, and those are organized based on the hash code of the key.
  • Hashtable is a non-generic type of collection, so we need to cast hashtable items to appropriate data types before we use it in our application.
  • Hashtable will allow us to store duplicate values, but keys must be unique to identify the hashtable values.
  • In hashtable, the key cannot be null, but the value can be null.
  • You can access hashtable elements either by using keys or with a foreach loop. In the foreach loop, you need to use DictionaryEntry to get key/value pairs from the hashtable.