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

Classes in C# Explained

C# Class Explained A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity, as explained by Guru99 . For instance, if you want to work with Guest’s data as in our previous DataDriven Web application . The properties of the Guest would be the Id, GuestName, Address, Phone number etc of the Guest. The methods would include the entry and modification of Guest data. All of these operations can be represented as a class in C# as shown below. using System; namespace CsharpnaijaClassTutorial {     public class Guest     {         public int Id { get ; set ; }         public string GuestName { get ; set ; }         public string Address { get ; set ; }         public string WhomToSee { get ; set ; }     ...

ASP.NET MVC Views

Views in ASP.NET MVC Application explained Find a related article By  Steve Smith  and  Luke Latham from Microsoft Corporation here In the Model-View-Controller (MVC) pattern, the  view  handles the application's data presentation and user interaction. A view is an HTML template with embedded  Razor markup . Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET MVC, views are  .cshtml  files that use the  C# programming language  in Razor markup. Usually, view files are grouped into folders named for each of the application's  controllers . The folders are stored in a  Views  folder at the root of the application as shown: The  Home  controller is represented by a  Home  folder inside the  Views  folder.  The  Home  folder contains the views for the  About ,  Contact , and  Index...

ASP.NET MVC Routing

ASP.NET MVC Routing ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match. Routing pattern is as follows A URL is requested from a browser, the URL is parsed (that is, break into controller and action), the parsed URL is compared to registered route pattern in the framework’s route table, if a route is found, its process and send response to the browser with the required response, otherwise, the HTTP 404 error is send to the browser. Route Properties ASP.NET MVC routes are res...