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 hastable object will contain a buckets to store an elements of collection. Here, 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 element.

 

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

 

When compared with dictionary object, 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 a values from hashtable.

C# HashTable Declaration

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

 

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

 

Hashtable htbl = new Hashtable();

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

C# HashTable Properties

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

 

PropertyDescription
Count It is used to get the number of key/value pair elements in hashtable.
IsFixedSize It is used to get a value to indicate that the hashtable has fixed size or not.
IsReadOnly It is used to get a value to indicate that the hashtable is readonly or not.
Item It is used get or set the value associated with the specified key.
IsSynchronized It is used to get a value to inidicate that an access to 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

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

 

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

C# Add Elements to HashTable

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

 

In hashtable, we can add a key/value pair elements of different data types. Following is the example of adding an elements to 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 key not exist, then that key adds a new key/value pair.

            htbl[3] = "Tutorials";

            // Add method will throws an exception if key already exists in hash table

            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 above example, we created a new hastable (htbl) and adding a different data type elements (key/value) to hashtable (htbl) in different ways. As discussed, Add method will throw an exception in case if we try to add a key (2) which is already existing so to handle that exception we used a try-catch block.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Add Elements to HashTable Example Result

 

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

 

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

 

Hashtable htbl = new Hashtable(){

                                {"msg", "Welcome"},

                                {"site", "Tutlane"},

                                {1, 20.5},

                                {2, null}

                            };

C# Access HashTable Elements

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

 

Following is the example of accessing a 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 above example, we are accessing hashtable elements in different ways by using keys, foreach loop and with available properties (Keys, Values) based on our requirements.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Access HashTable Elements Example Result

C# Remove Elements from HashTable

In c#, we can delete an elements from hashtable by using Remove() method. Following is the example of deleting an elements from hashtable in 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 above example, we used a Remove() method to delete particular value of element from hashtable using keys.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Remove HashTable Elements Example Result

 

In case, if you want to remove all the elements from hashtable, then use Clear() method.

C# HashTable Check If Element Exists

By using Contains(), ContainsKey() and ContainsValue() methods, we can check whether the specified element exists in hashtable or not. In case, if 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 exists in 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 above example, we used a Contains(), ContainsKey() and ContainsValue() methods to check for a particular keys and values exists in hashtable (htbl) or not.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Check Elements Exists in Hashtable or Not Example Result

C# HashTable Overview

Following are important points which needs 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 type before we use it in our application.
  • Hashtable will allow us to store a duplicate values but keys must be unique to identify the values in hashtable.
  • In hashtable the key cannot be null but the value can be null.
  • We can access hashtable elements either by using keys or with foreach loop. In foreach loop we need to use DictionaryEntry to get a key/value pairs from hashtable.
 

PREVIOUS

C# Arraylist