Skip to main content

HashTable in C# with Example

 HashTable in C# with Example

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

 Generally, the hashtable object will contain buckets to store elements of the collection. The bucket here, 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#, hashtable is same as a dictionary object but the only difference is that 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 are storing or retrieving values from the hashtable.

 C# HashTable Declaration

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 earlier, the collection is a class so to define a hashtable, you just need to declare an instance of the hashtable class before we perform any operations like add, delete, etc.

 Hashtable hashTable = new Hashtable();

 HashTable Properties

The following are some of the commonly used properties of hashtable in C#.

 

Property

Description

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 that the hashtable has fixed size or not.

IsReadOnly

It is used to get a value to indicate that 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 that 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.

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#.

 

Method

Description

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 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.

Adding Elements to HashTable

While adding elements to hashtable we need to make sure that there will be no any duplicate keys because hashtable will allow us to store duplicate values but keys must be unique to identify the values in the hashtable.

 

In hashtable, we can add a key/value pair elements of different data types as ca be seen in the following example using C#.

 

using System;

using System.Collections;

namespace CsharpnaijaTutorial

{

    class Program

    {

        static void Main(string[] args)

        {

            Hashtable hashTable = new Hashtable();

            hashTable.Add("message", "Welcome");

            hashTable.Add("web site", "Csharp naija");

            hashTable.Add(1, 20.5);

            hashTable.Add(2, null);

            // Another way to add elements. If key not exist, then that key adds a new key/value pair.

            hashTable [3] = "Tutorials";

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

            try

            {

                hashTable.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 hashTable)

            {

                Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);

            }

            Console.ReadLine();

        }

    }

}

 

From above example, we created a new hastable (hashTable) and adding a different data type elements (key/value) to hashtable (hashTable) 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 as can be seen in the output below.

 

Csharpnaija_hashtable_example

Removing Elements from HashTable

In C#, you can delete elements from hashtable by using the Remove() method. The following example shows how to use the delete method to delete elements from hashtable.

 

 

using System;

using System.Collections;

 

namespace CsharpnaijaTutorial

{

    class Program         

    {

        static void Main(string[] args)

        {

            Hashtable htbl = new Hashtable();

            htbl.Add("message", "Welcome");

            htbl.Add("website", "Csharp naija");

            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();

        }

    }

}

 

We use the Remove method to delete the first and the second elements in the hashtable collection as shown in the image below.

 

csharpnaija_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.

 

The 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 CsharpnaijaTutorial

{

    class Program

    {

        static void Main(string[] args)

        {

            Hashtable htbl = new Hashtable();

            htbl.Add("message", "Welcome");

            htbl.Add("website", "Csharp naija");

            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 'Csharp naija': {0}", htbl.ContainsValue("Csharp naija"));

            Console.ReadLine();

        }

    }

}

 

From above example, we used a Contains(), ContainsKey() and ContainsValue() methods to check for a particular keys and values exists in hashtable (htbl) or not as can be seen from the the output screen shown below.

 

csharpnaija_hashtable_contain


 

Thank you

 

References

 

1.     Tutlane

2.     TutorialTeacher

3.     TutorialPoint

 

Comments

Popular posts from this blog

The String.Join Method in C# Explained

The String.Join Method in C#   The string.Join concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. Overloads of string.Join Method Description Join(Char, Object[]) Concatenates the string representations of an array of objects, using the specified separator between each member. Join(Char, String[]) Concatenates an array of strings, using the specified separator between each member. Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, usi...

Most Popular Programming Languages in 2020

Most Popular Programming Languages in 2020 In this blog post, you will learn about the most popular programming languages in 2020 for creating the best web applications. Check its pros and cons. Analyzed by technostacks Not very long ago, just a few people were considered to be computer programmers, and the general public viewed them with awe. In this digital age that we are now living in, however, a large number of IT jobs need a solid grasp of one or more programming languages. Whether one wants to develop a mobile app or get a certification for having programming knowledge, or even to learn new skills, one needs to opt for the right programming language. Below mentioned eight most popular programming languages which are in demand for software development and web applications. This is the most used programming languages in 2019 and will be in 2020. For each, there is little information about the language, benefits and its complexity, as well as about its usage. One must...