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

Collections in C#

Collections in C# In our previous article , we have learned about how we can use arrays in C#. Arrays in programming are used to group a set of related objects. So one could create an array or a set of Integers, which could be accessed via one variable name. What is Collections in C#? Collections are similar to Arrays, it provides a more flexible way of working with a group of objects. In arrays, you would have noticed that you need to define the number of elements in an array beforehand. This had to be done when the array was declared. But in a collection, you don't need to define the size of the collection beforehand. You can add elements or even remove elements from the collection at any point of time. This article will focus on how we can work with the different collections available in C#. There are three distinct collection types in C#: standard generic concurrent The standard collections are found under the System.Collections. They do not store elemen...

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

System.IO Namesapce in C#

  System.IO Namesapce in C# A  file  is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a  stream . The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the  input stream  and the  output stream . The  input stream  is used for reading data from file (read operation) and the  output stream  is used for writing into the file (write operation). From the above definition of file, the C# provides a namespace that enable us to manipulate file in C# called System.IO.   System.IO  is a  namespace  and it contains a standard IO (input/output) types such as classes , structures , enumerations , and  delegates  to perform a read/write operations on different sources like file, memory, network, etc.   System.IO Classes The table below shows differen...