Working with Hashtables in .NET

Introduction

There are millions of Namespaces in the .NET Framework, as we all know. Coming from a VB 6 background, I was accustomed to arrays and arrays only. Luckily all has changed with .NET, in that the .NET Framework supports Collections.

What are Collections?

As the name implies, it is a collection of objects. You have a collection of CD’s or DVD’s or stamps for example. Now with the .NET Framework Collections Namespace, you could store a collection of objects in a certain manner.

Available Collection Classes

The following classes form part of the Collections Namespace :

  • ArrayList
  • BitArray
  • CaseInsensitiveComparer
  • CaseInsensitiveHashCodeProvider
  • CollectionBase
  • Comparer
  • DictionaryBase
  • Hashtable
  • Queue
  • ReadOnlyCollectionBase
  • SortedList
  • Stack
  • StructuralComparisons

You can find their associated members and properties, from this MSDN link

What is a Hashtable?

If you haven’t navigated to the above link, a Hashtable ( apart from being my favourite Collection class ) simply represents a collection of key / value pairs that are organized based on the hash code of the key. In layman’s terms this stores a collection of information, based on a certain key.

Still complicated?

OK, here is a very small example of what I mean :

//C#
hteNumbers_ENG["0"] = "zero"; //Store the word "zero" inside the hashtable at location "0"
'VB
hteNumbers_ENG("0") = "zero" 'Store the word "zero" inside the hashtable at location "0"

Here, hteNumbers is our Hashtable object. The key in the above example is 0. The value is “zero”. Now, the key can be named anything, as long as it makes sense, but with our practical examples, you will see that there is a method to my madness. You can also have a look at this MSDN link, pertaining to the Hashtable specifically.

Let us put the Hashtable’s powers to good use and create our sample project. You could use either C# or VB.NET as I will demonstrate the code of both.

Design

Start Visual Studio and create a new Windows Forms Project. You can name it anything you want. Just note that my VB.NET version is named HashTable_Ex and my C# version is named HashTable_C_Ex. Design the form so that it represents the next picture :

Design of our Project
Figure 1 Design of our Project

Leave the default names.

Coding

As usual, we need to start with the Namespaces.

In VB.NET add this Imports :

Imports System.Collections 'The System.Collections namespace contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hashtables and dictionaries.

In C# add the following using(s) :

using Microsoft.VisualBasic; //Need to add reference as well
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
//The System.Collections namespace contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hashtables and dictionaries.

You might notice the very top using. This makes it easier for us to make use of VB’s InputBox method, seeing the fact that C# doesn’t have such a method built in. I know, it may not be the best practice, but I’m trying to make these samples as easy and light as possible. You need to add a manual reference to Microsoft.VisualBasic as well, by clicking Project->Add Reference->.NET tab.

We need the Collections namespace so that we can utilize its Hashtable classes.

Add the following class level variables.

VB.NET:

    Private hteNumbers_ENG As Hashtable = New Hashtable 'Represents a collection of key-and-value pairs that are organized based on the hash code of the key.
    Private hteNumbers_AFR As Hashtable = New Hashtable
    Private strNumber As String 'Input Number

C#:

        private Hashtable hteNumbers_ENG = new Hashtable(); //Represents a collection of key-and-value pairs that are organized based on the hash code of the key.
        private Hashtable hteNumbers_AFR = new Hashtable();

        private string strNumber; //Input Number

Next, let us add the Form_Load event procedures, so that we can initialize our hashtable objects with values.

VB.NET :

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        hteNumbers_ENG("0") = "zero" 'Store the word "zero" inside the hashtable at location "0" etc.
        hteNumbers_ENG("1") = "one"
        hteNumbers_ENG("2") = "two"
        hteNumbers_ENG("3") = "three"
        hteNumbers_ENG("4") = "four"
        hteNumbers_ENG("5") = "five"
        hteNumbers_ENG("6") = "six"
        hteNumbers_ENG("7") = "seven"
        hteNumbers_ENG("8") = "eight"
        hteNumbers_ENG("9") = "nine"

        hteNumbers_AFR("0") = "nul" 'Do the same with the Afrikaans numbers
        hteNumbers_AFR("1") = "een"
        hteNumbers_AFR("2") = "twee"
        hteNumbers_AFR("3") = "drie"
        hteNumbers_AFR("4") = "vier"
        hteNumbers_AFR("5") = "vyf"
        hteNumbers_AFR("6") = "ses"
        hteNumbers_AFR("7") = "sewe"
        hteNumbers_AFR("8") = "agt"
        hteNumbers_AFR("9") = "nege"
    End Sub

C# :

        private void Form1_Load(object sender, EventArgs e)
        {
            hteNumbers_ENG["0"] = "zero"; //Store the word "zero" inside the hashtable at location "0"  etc.
            hteNumbers_ENG["1"] = "one";
            hteNumbers_ENG["2"] = "two";
            hteNumbers_ENG["3"] = "three";
            hteNumbers_ENG["4"] = "four";
            hteNumbers_ENG["5"] = "five";
            hteNumbers_ENG["6"] = "six";
            hteNumbers_ENG["7"] = "seven";
            hteNumbers_ENG["8"] = "eight";
            hteNumbers_ENG["9"] = "nine";

            hteNumbers_AFR["0"] = "nul"; //Do the same with the Afrikaans numbers
            hteNumbers_AFR["1"] = "een";
            hteNumbers_AFR["2"] = "twee";
            hteNumbers_AFR["3"] = "drie";
            hteNumbers_AFR["4"] = "vier";
            hteNumbers_AFR["5"] = "vyf";
            hteNumbers_AFR["6"] = "ses";
            hteNumbers_AFR["7"] = "sewe";
            hteNumbers_AFR["8"] = "agt";
            hteNumbers_AFR["9"] = "nege";
        }

What I have done here was to initialize the two hashtable objects. The one object contains the English words for their associated keys, whereas the second hashtable object contains the Afrikaans words. This means when we look for key named “9” we will get “nine” for English or “nege” for Afrikaans.

Now we need a way to input numbers, and this is as easy as…

VB.NET:

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        strNumber = InputBox("Enter a sequence of numbers.")

    End Sub

C# :

        private void Button2_Click(object sender, EventArgs e)
        {
            strNumber = Interaction.InputBox("Enter a sequence of numbers.");
        }

This makes use of the InputBox Visual Basic statement to store the number inside strNumber. For more clarity on the Interaction.InputBox method, have a look here.

This code will produce an InputBox into which you can enter your numbers, as in Figure 2:

InputBox
Figure 2InputBox

Now, the fun part! We need to make use of the Hashtable. The whole objective of this sample was to have a quick way to translate input numbers to their word counterparts. I needed such functionality some time ago in one of my projects at work. This is slightly edited from the original version, which had to compensate for all South Africa’s 11 official languages. There were other terms in my original program as well.

With this project, I realized the power of Hashtables, and yet, they are so simple to use! A normal array didn’t give me all the functionalities I needed. Yes, I suppose arrays could have worked, but much much more difficult. If you are under pressure and need a quick dictionary type list, Hashtables are your answer.

Anyways, let us add the last code segments.

VB.NET :

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If strNumber <> "" Then 'If number was entered into InputBox
            If CheckBox1.Checked Then 'If CheckBox is checked
                For Each c As Char In strNumber 'Loop through entered text
                    Dim digit As String = c.ToString 'Convert to string

                    If hteNumbers_ENG.ContainsKey(digit) Then 'if Entered text is any of the keys
                        ListBox1.Items.Add(hteNumbers_ENG(digit)) 'Add to listbox

                    End If
                Next
            Else 'CheckBox not checked, default to Afrikaans language..
                For Each c As Char In strNumber
                    Dim digit As String = c.ToString

                    If hteNumbers_AFR.ContainsKey(digit) Then
                        ListBox1.Items.Add(hteNumbers_AFR(digit))
                    End If
                Next

            End If
        End If
    End Sub

C# :

        private void Button1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(strNumber)) //If number was entered into InputBox
            {
                if (CheckBox1.Checked) //If CheckBox is checked
                {
                    foreach (char c in strNumber) //Loop through entered text
                    {
                        string digit = c.ToString(); //Convert to string

                        if (hteNumbers_ENG.ContainsKey(digit)) //if Entered text is any of the keys
                        {
                            ListBox1.Items.Add(hteNumbers_ENG[digit]); //Add to listbox

                        }
                    }
                }
                else
                {
                    foreach (char c in strNumber)
                    {
                        string digit = c.ToString();

                        if (hteNumbers_AFR.ContainsKey(digit))
                        {
                            ListBox1.Items.Add(hteNumbers_AFR[digit]);
                        }
                    }

                }
            }
        }

After the Process button is clicked, your ListBox will be populated by the lists stored inside the Hashtable. Figures 3 and 4 show what it will look like:

The English List
Figure 3The English List

The Afrikaans List
Figure 4The Afrikaans List

I am attaching the samples with this article as well.

Conclusion

I hope that with this short article, you have seen how powerful Hashtables are, and how simple they are to use. Until next time!

Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read