How to Add Items to Hashtable Collection in C#


We have already discussed the basics of hashtables. A hashtable collection in C# is used to store key−value pairs wherein each of these key-value pairs is organized based on the hash code of the key. This hash code is calculated using a hash code function. Internally, the hashtable uses buckets to store data. A bucket is nothing but a virtual group of elements within the hashtable. A hash code is associated with each bucket.

Programmatically, a hashtable is similar to a dictionary object but unlike in dictionary object, a hashtable can store objects of different data types. Performance−wise, hashtables exhibit low performance as data elements of hashtables are objects. Hence the boxing and unboxing of objects have to be performed for the storage and retrieval of values from the hashtable.

In this article let’s discuss how we can add items to the hashtable collection.

How to Add Items to the Hashtable Collection?

The hashtable collection in C# is implemented using the hashtable class. This class provides various methods to perform different operations on hashtables. One such method is Add().

The Add() method of the hashtable class is used to add elements with the specified key and its corresponding value in a hashtable. When adding key-value pairs to the hashtable, we should ensure that the keys are not duplicated or null as the hashtable allows only non-null and unique keys.

In the hashtable collection of C#, we can have key/value pair elements of different data types.

Let’s move on to Add() method now.

The general prototype of Add() method of hashtable collection is given below.

Syntax

public virtual void Add(object key, object value);

Parameters

  • Key − the specified key(type System.Object) of the element being added.Should be non-null.

  • Value − the specified value of the element (type System.Object) This value can be null.

Exceptions: This method throws the following exceptions.

  • ArgumentNullException − When the key is null.

  • ArgumentException − an element already exists with the same key.

  • NotSupportedException − Hashtable has a fixed size or is read-only.

If we have a hashtable object declared as follow −

Hashtable hshTable = new Hashtable();

Then we can add an element to this hashtable object using the Add() method as follows −

hshTable.Add("msg", "charVal");

Since hashtable allows elements of mixed data types, we can add a numeric value as well in the same hashtable −

hshTable.Add(1, 2022);

Instead of using Add() method, we can also assign the values directly to the hashtable. For example, for adding an element with key = 2, we can simply write,

hshTable[3] = "three";

The above statement will create a key-value pair (3,” three”) in the hashtable.

Programming Examples for Adding Items to Hashtable Collection

The following program shows the Add() method demonstration to build a hashtable of different elements.

Example 1

using System;
using System.Collections;
class Program {
   static void Main(string[] args) {
      Hashtable mixedHashTable = new Hashtable();
      //add method
      mixedHashTable.Add("msg", "Collection");
      mixedHashTable.Add("site", "HashTable");
      mixedHashTable.Add(1, 3.14);
      mixedHashTable.Add(2, null);

      //assign value to the key
      mixedHashTable[3] = "Tutorial";

      // Add method throws an exception if the key already exists in //hashtable
      try {
         mixedHashTable.Add(2, 750);
      } catch {
         Console.WriteLine("Hashtable already has an element with Key = '2'.");
      }
      Console.WriteLine("*********HashTable Elements********");
      // It will return elements as Key-Value Pair.
      foreach (DictionaryEntry elem in mixedHashTable) {
         Console.WriteLine("Key = {0}, Value = {1}", elem.Key, elem.Value);
      }
      Console.ReadLine();
   }
}

The above program creates a hashtable object first using the default constructor. Then it uses the Add() method to add different elements to the hashtable. We can also add elements to the hashtable by assigning the value directly. The above program adds key-value pairs of different data types to the hashtable. Then using an iterator, the elements of the hashtable are displayed one by one.

Output

The output of the above example is as shown below −

Hashtable already has an element with Key = '2'.
*********HashTable Elements********
Key = 2, Value = 
Key = msg, Value = Collection
Key = 3, Value = Tutorial
Key = site, Value = HashTable
Key = 1, Value = 3.14

The output shows all the key-value pairs that we had added to the hashtable.

Let’s take another example of adding elements to the hashtable. The program is given below.

Example 2

using System;
using System.Collections;
class hTable {
   // Driver code
   public static void Main() {
      // Creating a Hashtable
      Hashtable strHashTable = new Hashtable();

      // Adding elements in Hashtable
      strHashTable.Add("4", "Even Number");
      strHashTable.Add("9", "Odd Number");
      strHashTable.Add("5", "Odd and Prime Number");
      strHashTable.Add("2", "Even and Prime Number");

      // Get a collection of the keys.
      ICollection c = strHashTable.Keys;

      // Displaying the hashtable contents
      Console.WriteLine("=========Contents of the Hashtable=========");
      foreach(string str in c)
         Console.WriteLine(str + ": " + strHashTable[str]);
   }
}

In this program, we are adding the value of the type string. We use the Add() method for adding values and then retrieve the collection of keys in the hashtable. Using a foreach loop, we then traverse this key collection and display each key along with its corresponding value.

Output

The output generated is as follows −

=========Contents of the Hashtable=========
5: Odd and Prime Number
9: Odd Number
2: Even and Prime Number
4: Even Number

In this manner, we can add items to the hashtable collection using the Add() method of the hashtable class.

We have seen how to add items to the Hashtable Collection in this article. In future articles, we will discuss more operations on Hashtable.

Updated on: 14-Dec-2022

471 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements