Udemy logo

hashtable in c#C# was made to work with Microsoft’s .NET framework in the year 1993 by a Dutch programmer called Anders Hejlsberg. Using C#, you can make secure, robust applications that can be run on any system, regardless of the architecture. The syntax of the language is easy to understand and simple to use. If you’ve learned C or a related language before, chances are you will pick up C# in no time – especially with this C# course designed to help you ramp up in just one hour. C# is an object oriented language, which means that is supports inheritance, polymorphism and encapsulation. Object oriented languages are efficient and can be used to make powerful applications in general, and C# is no exception to the rule. With C#, you can make client-server applications, XML Web apps, Windows apps, components and database related applications. This course even shows you how to write your own Android Apps in C#.

In this tutorial, we’re going to take a look at the hashtable class in C#. You’ll need to be familiar with the basics of the language to understand this tutorial. You may want to check out this beginners course in C# before we move on.

What is a Hash table?

So what exactly is a hash table? A hash table is made up of a mapping function and an array. The array contains your data, while the mapping function is used to assign numerical values (keys) to the data. This helps in categorizing the data, which speeds up search times when you search for it. This is, of course, a simplified explanation of a hash table – a real hash table is much more complicated than that. For example, the hash function should assign unique keys to each bucket (data slot), but in practice a pair of keys might get hashed to the same table. This is known as a hash collision, and the design of the hash table must be able to take this probability into account. Hashtables are much more efficient than most other search trees when it comes to finding data. They are used in all kinds of computer software – especially database software. If you’ve worked with database software before, like Oracle, you’ve probably worked with hash tables too.

Creating a Hashtable Object with the Hashtable Class in C#

The hashtable class in C# is used to create a hash table. The syntax to create a new hash table is:

public Hashtable name_of_hashtable = new Hashtable ();

When you create a new hashtable, it is empty. Let’s create a hashtable called hashtableexample and place three integer keys inside it:

using System.Collections;
using System;
class Example
{
    static void Main()
    {
                Hashtable hashtableexample = new Hashtable();
                hashtableexample[1] = "One";
                hashtableexample[3] = "Three";
                hashtableexample[29] = "Twenty-Nine";
                foreach (DictionaryEntry entry in hashtableexample)
                {
                    Console.WriteLine("{0} : {1}", entry.Key, entry.Value);
                }
    }
}
Output:
29: Twenty-Nine
3: Three
1: One

In this program, we have created a class called Example to hold the hashtable named hashtableexample. We added three integer keys to that hashtable, with different entry key numbers and values. The integer keys we added belong to the DictionaryEntry type, which contains keys and their corresponding values. We added three keys with different key entries and values. In the final part of the program, we printed the keys with the corresponding values to the screen using the foreach loop.

It’ll be easier to learn the language as a whole instead of bits and pieces, so we recommend you check out this advanced course in C# to learn more about hashtables.

Adding Entries to a Hash Table

Now that we know how to add keys to a hash table, let’s see how to add entries to it. The syntax to add an item to a hashtable object is:

name_of_hashtable.Add(Parameter 1 (Data), Parameter 2 (Data))

You’d understand the syntax better with an example program. We’ll write a simple hashtable that contains the name of three authors and the number of books they’ve sold recently:

using System.Collections;
using System;
class Example
{
    static void main()
    {
                // Creating a simple hashtable called hashtableexample.
                Hashtable hashtableexample = new Hashtable();
                hashtableexample.Add("JKRownling", 5000);
                hashtableexample.Add("JArcher", 3000);
                hashtableexample.Add("AChristie", 1000);
    }
}

We created a simple hashtable with three entries inside it. As you can see, we used string values as well as integer values. Both your entries could have contained string or integer values. You can try writing the hashtable to the screen to see what it looks like (using the foreach loop, as we showed you earlier).

Hashtable Methods

There are several methods that you can use with the hashtable class. The Add method, for example, adds an entry to the hashtable class (like in the program above), the Clear method can be used to wipe the hashtable clean, the Clone method creates a copy (shallow) of your hashtable and the GetHash method returns the hashcode for a specific key. You will need to get familiar with most of the hashtable methods if you’re going to get a good grasp on hashtables and handle them properly. You can check out the different methods in the official documentation on the Microsoft Office website. Learn more about these methods in detail with this C# course.

We’ll write a simple program that demonstrates the use of the Contains method to help you understand the concept better. We’ll just extend the program we wrote earlier:

using System.Collections;
using System;
class Example
{
static Hashtable GetHashtable()
    {
                // Creating a simple hashtable called hashtableexample.
                Hashtable hashtableexample = new Hashtable();
                hashtableexample.Add("JKRowling", 5000);
                hashtableexample.Add("JArcher", 3000);
                hashtableexample.Add("AChristie", 1000);
                return hashtableexample;
   }
static void Main ()
{
Hashtable hashtableexample = GetHashtable ();
Console.WriteLine(hashtableexample.Contains (“JKRowling”));
}
Output:
True

The Contains method checks the hash table to see if a specific key is present. If it is, it will return a true value. If not, it returns a false value. We created a simple hash table called hashtableexample and then returned its value. We then checked to see if any of the keys in the hash table match “JKRowling” with the Contains method.

C# also has a newer, much more efficient class called the Dictionary collection which is quite similar in functionality. If you’re going to operate or maintain one of those programs for a company, you need to know about the hashtable class. The .NET framework makes C# sharp portable and platform independent, just like Java.  There is a growing demand for C# programmers in the industry and a shortage of good programmers. You may want to explore C# programming as a career option. This three part course gets into the details of C#(Part I, Part II, Part III) – from the basics to the advanced concepts – to help you along your journey.

Page Last Updated: April 2014

Top courses in C# (programming language)

Ultimate C# Masterclass for 2023
Krystyna Ślusarczyk
4.7 (1,018)
Bestseller
C# / .NET Interview Questions with Answers.
Shivprasad Koirala
4.7 (1,248)
Complete C# Unity Game Developer 3D
Ben Tristem, Rick Davidson, GameDev.tv Team, Gary Pettie
4.7 (40,251)
Bestseller
Learn Parallel Programming with C# and .NET
Dmitri Nesteruk
4.4 (3,532)
Bestseller
Unity RPG Inventory Systems Asset Pack: Behind The Scenes
GameDev.tv Team, Rick Davidson
4.3 (837)
The Unity C# Survival Guide
Jonathan Weinberger, Unity Technologies, GameDevHQ Team
4.7 (1,731)
C#/.NET - 50 Essential Interview Questions (Mid Level)
Krystyna Ślusarczyk
4.8 (206)
Bestseller
Design Patterns in C# Made Simple
Zoran Horvat
4.7 (401)
Complete C# Masterclass
Denis Panjuta, Tutorials.eu by Denis Panjuta
4.6 (27,217)
Design Patterns in C# and .NET
Dmitri Nesteruk
4.3 (11,215)
Bestseller

More C# (programming language) Courses

C# (programming language) students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo