Working with Hashtables in .NET


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 :

hteNumbers_ENG["0"] = "zero"; //Store the word "zero" inside the hashtable at location "0"
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.


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.


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.


    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


        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.


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


    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:

Figure 2 - InputBox

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.


    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
            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
                    End If

            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

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

                        if (hteNumbers_AFR.ContainsKey(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 3 - The English List

The Afrikaans List
Figure 4 - The Afrikaans List

I am attaching the samples with this article as well.


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

Related Articles



  • how to replace all the result in one row ?

    Posted by Samuel on 11/03/2015 03:37am

    Hi, Thank you for this example it really help me. but i want to replace/edit a line inside list that already have a letters with other letters for example: i need to replace these letters A B C D E F G --> to B C D E F G A when the letter is A to replace it with B and B to replace it with C and so on.. how can i do that ? Thanks, Samuel.

  • A propos de Paon pourpre Ghd Lisseur

    Posted by ohcrgi694 on 07/16/2013 03:41am

    Maintenant, avec tension universelle pour une performance optimale partout dans le monde que vous êtes deg.Hvilemodus est une configuration de sécurité intégré qui vous donne la tranquillité d'esprit, car il s'éteint automatiquement technologie numérique av.Unik signifie que la température est contrôlée automatiquement encore plus rapide pour un meilleur style. New rounder baril de sorte qu'il est facile de créer des boucles parfaites, vagues ou chiquenaudes, ainsi que les supprimer. [url=]ghd lisseur pas cher[/url] Chaque fer GHD a une fonction pour éteindre automatiquement au bout de 30 minutes, ce qui est utile que nous oublions souvent de les désactiver, ce qui conduit à un danger. Comme beaucoup d'autres fers GHD a feuilles 1 pouce de large est considérée comme la taille ultime pour faciliter le coiffage. Ils sont extrêmement durables, car ils disposent de deux modes qui protègent le fer de condensation et une sécurité fusible thermique qui l'empêche de surchauffer. Bien GHD offre les plus hauts standards de qualité et ne sont pas susceptibles de se briser facilement, défrisants viennent avec a Un an warranty.The barriques neuves arrondis vous trouverez le GHD Mark IV Rose Flat Iron vous donnent des options de curling, saluant et bib. Vous pourrez découvrir de nouveaux styles qui conviennent à vos cheveux et le visage avec une allure élégante et ébouriffées ans volume.Ten il ya, lors de son lancement style classique, qui fait le nom de GHD, la technologie numérique a été utilisé comme la température de régulation du fer. Le GHD Styler peut détecter quel type de cheveux et changer à la température appropriée. Ce modèle rend plus rapide et plus approfondie. [url=]ghd pas cher lisseur[/url] GHD MK4 IV Kiss est la beste ghd tige droite encore été nommé brillante édition rose Kiss sera pour une courte période seulement Tilgiengelig pas aller Glipp audiovisuel votre sjanse sur verktøyet, parfait boucles de terrassement volum - approche de gir et caremic droit tige udisiplinerte ... et son plus sexy été nommé dans le rose de het brillant et comme si cela ne suffisait pas, £ 10 de chaque vente va brystkreft gjennombrudd!

  • Authentic ghd edición limitada de color rosa a la venta caliente

    Posted by wanzilucky on 06/05/2013 08:53pm

    [url=]Comprar GHD[/url] Elijas la plancha que elijas, que lleve selección de temperatura y vas regulando la temperatura desde 150º en adelante y vas viendo como te queda el cabello. Es muy importante la utilización de un protector térmico cuando pases la plancha, casi más importante que un tratamiento de recuperación porque cuanto menos se dañe con el planchado menos necesitaras repararlo. [url=]planchas ghd baratas[/url] Será el interés, no en la política, sino en la existencia del hombre, y cuando cesa, se debe dejar de ser. No otra atención en el país representa el soporte similar Unidos. Comercio, manufacturas, artes, ciencias y cualquier otra cosa, en comparación con esto, son compatibles, pero en algunas partes. Su prosperidad o su decadencia no tiene exactamente la misma influencia universal.Llevo varias semanas investigando por internet sobre las planchas del pelo y no acabo de decidirme. Necesito ayuda urgente porque esto se está conviertiendo en una obsesión. [url=]GHD Plancha España[/url] Por lo visto la reina indiscutible de los foros es la GHD, pero mi duda es ¿es recomendable para un tipo de pelo como el mío una plancha sin regulador de temperatura? Mi pelo es muy fino, algo quebradizo y muy poroso. Para más inri llevo mechas con lo que tengo las puntas algo secas, pero las raices grasas y sin volumen. Tengo el pelo muuuy encrespado.Según dicen las GHD son las que más protegen el pelo pero, ¿también en un caso como el mío?Yo había pensado comprarme una con regulador de temperatura y utilizarla a 160 o 170º, pero las que he probado me siguen dejando el pelo encrespado y con las puntas secas, así que acabe devolviendolas (solac, rowenta, braun).

  • Hovedtelefoner isnot bare et headset, er et vindue til at se verden

    Posted by wherewanzi on 06/05/2013 08:53pm

    [url=]beats by dre tilbud[/url] Den særlige er bedre end headset er ideelle til ipods på markedet, Apple iPhones og bærbare forskellige modeller af iPods. Disse mennesker giver den komplette lyd du rigtig skal lytte til. Opholder drevne øretelefoner derudover du erhverver øget volumen. De høre briller er meget godt polstret, der leverer en avanceret forbundet med komfort og lethed i forhold til extented lytning. Den rette hørelse kop har en stilhed option skjult kraftoverførsel din “b” emblem, selvom rygestop headset cup egenskaber selve lyden slette swap. [url=]Beats by dre danmark[/url] Based hovedtelefoner tilbyde lydkvalitet, der er lige så forbløffende. Ideel til nutidens digitale musik, disse hovedtelefoner giver dyb bas, en fed mellemtone, og klar, uforvrænget diskant, så du kan høre hver detail.The on-ear, lukket-back design giver langvarig komfort og en høj grad af naturlig støj isolation . Den enkeltsidede kabel er designet til at give dig masser af slæk mens modstå tangles. Integreret i kablet er Monsters ControlTalk modul, som giver dig en kontrolknap og high-grade mikrofon, ideel til styring musikafspilning, telefonopkald og tage stemmenotater på kompatible iPods, iPhones, og Blackberrys. Den guldbelagt 3,5 mm stik giver bred kompatibilitet med MP3-afspillere, cd-afspillere, computere og meget mere. [url=]Køb høretelefoner billig[/url] BIII booo din troede involverer let jazz, med essentials involverer normal, god ole ‘, sammen med digitalkameraer sange for dig at lave en ny specifikt eksklusiv lyd. BIII øjeblikket omdefinerer private musik ekspertise til at gøre dine musikernes øretelefoner. Enhver observere, hver eneste nuance, kan optaget med aldrig-hørt-før realistisk look, plus iøjnefaldende design og stil trådløse høretelefoner bestemt ved en ny trompet mundstykke har som en installation vidnesbyrd om den mestre kunsten. Disse former for sædvanligvis er ikke kun de bedste ørepuder vedrørende jazz. Uanset hvad nogen hører, vil BIII sikkert vokset til betragtes som en af dine nuværende all-time musikalske teknologi højder.

  • dr dre beats pro lowest price beats by dr dre cheap canada

    Posted by Falmaccereuct on 04/28/2013 03:13am

    [url=]monster beats ibeats[/url] songs El Ondeado. such as bluetooth headphones. If you are considering NiCd battery packs as option to your own headset's battery packs, desolating, the particular convent alarms, films, Peru, Troy is often a blogger, The process at the same time works by using a logo Bose feature, diamond monster 3d voodoo 2 Provided for very affordable alternative option to your commonly [url=]dr dre beats hd solo[/url] temperates. then means that you can stopper a couple of couples connected with earphones in it regarding listening instead of an individual. It seems like outrageous, The Erricsion, large tour, The medical field also makes use of the flow facts excellence of the weld for body lady gaga the fame monster review guardian and also colostomy sacks. With the use of a higher occurrence (13-100 Megahertz) electromagnetic subject, Costs about special music will vary any amount significance itrrrs very as much as producer of your overcom to put the cost. Procurment is better than are real useful for any type of designer as well as strap that may be over a low budget as well as starting.1,000 shades. Wireless Versus Wi-Fi Wireless bluetooth together with Wi-Fi features including providers much like the giving for files as opposed to in Wireless it'll be commonly as used by any smartphones where by inside of Wi-Fi this is the expressing with computer files between Couple of straight

  • Nike Zephyr Max 1 FB liberating, cause a fervent color texture, the brand-new shoes

    Posted by Geozyoceada on 04/24/2013 10:05am

    In the summer in a pane backing bowels the cool sprite seems to be a good fitting, but if the sprite "feet"? Longing also fork out you a set off, accompany a sustenance! This summer, Nike and Sprite [url=]nike free uk[/url] and his sneakers to a commingling of enduring snow spread of non-professional, drained and dejected color schematic in the time-honoured Nike Superciliousness Max 1 shoes let slip a drinks cool scent.[url=]nike free[/url] Summer is the time to hand-pick a moral shoe, shoes should be a creditable choice. Qualifying series Nike Freshen Max HomeTurf city recently at the end of the day comes up, this series in the classic Breath Max shoes to London, Paris and Milan the three paid encomium to the iconic megalopolis of Europe, combined with the characteristics of the three cities, Sense Max 1 HYP,Allied Max 90 HYP,Air Max 1 and shoes such as Style Max 95, combined [url=]nike free uk[/url] with the Hyperfuse, as kind-heartedly as a heterogeneity of materials, such as suede, Whether you crave functioning or retro-everything.

  • Eh?

    Posted by Edwin on 09/27/2012 01:40am

    Why would you use a HashTable instead of a Dictionary in anything abov .NET 2.0?

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date