In C#, a Hashtable is a collection that stores key-value pairs. It uses a hash code to organize the keys for efficient data retrieval. The key can be any object, and each key is associated with a corresponding value. It is a part of the System.Collections namespace and is non-generic (which means it can store any kind of object as both the key and value).
- In Hashtable, the key cannot be null, but the value can be null.
- In Hashtable, key objects must be immutable as long as they are used as keys in the Hashtable.
- Hashtable can store elements of different types.
- In the Hashtable key must be unique, duplicated keys are not allowed.
- The elements of Hashtable that are key-value pair is stored as DictionaryEntry objects.
Example: This example demonstrates how to create a Hashtable, add key-value pairs to it, and iterate over the entries to display the content.
C#
// C# program to add elements to the hashtable
using System;
using System.Collections;
class Geeks {
static void Main()
{
// Create a new Hashtable
Hashtable ht = new Hashtable();
// Add key-value pairs to the Hashtable
ht.Add("One", 1);
ht.Add("Two", 2);
ht.Add("Three", 3);
Console.WriteLine("Hashtable elements:");
foreach(DictionaryEntry e in ht)
{
Console.WriteLine($"{e.Key}: {e.Value}");
}
}
}
OutputHashtable elements:
Two: 2
Three: 3
One: 1
Creating a Hashtable
In C#, the Hashtable class offers 16 different constructors each with its own use. For simplicity, we will focus on the most commonly used constructor which is Hashtable().
Hashtable(): This constructor is used to create an instance of the Hashtable class which is empty and has the default initial capacity, load factor, hash code provider, and compare.
Let’s see how to create a Hashtable using Hashtable() constructor:
Step1: Include the System.Collections namespace in your program with the help of using keyword.
using System.Collections;
Step 2: Use the Hashtable() constructor to create an empty Hashtable.
Hashtable ht = new Hashtable();
Performing Different Operations on Hashtable
1. Adding Elements: We can add elements in the Hashtable using Add() method.
Example: Here, this program demonstrates how to create and add elements to the Hashtable.
C#
// Add Elements in Hashtable
using System;
using System.Collections;
class Geeks {
// Main Method
static public void Main()
{
// Create a hashtable using the Hashtable class
Hashtable h1 = new Hashtable();
// Adding key/value pairs using Add() method
h1.Add("1", "Welcome");
h1.Add("2", "to");
h1.Add("3", "GeeksforGeeks");
Console.WriteLine("Key and Value pairs from h1:");
// Iterating through the hashtable using
// DictionaryEntry
foreach(DictionaryEntry ele1 in h1)
{
Console.WriteLine("{0} and {1}", ele1.Key,
ele1.Value);
}
// Create another hashtable using the Hashtable
// class and a collection initializer
Hashtable h2 = new Hashtable() {
{ 1, "hello" }, { 2, 234 }, { 3, 230.45 },
{
4, null
}
};
Console.WriteLine(
"Key and Value pairs from h2:");
// Iterating through the hashtable using the Keys
// collection
foreach(var ele2 in h2.Keys)
{
Console.WriteLine("{0} and {1}", ele2,
h2[ele2]);
}
}
}
OutputKey and Value pairs from h1:
3 and GeeksforGeeks
2 and to
1 and Welcome
Key and Value pairs from h2:
4 and
3 and 230.45
2 and 234
1 and hello
2. Removing Elements: The Hashtable class provides two different methods to remove elements and the methods are:
- Clear(): This method is used to remove elements from the Hashtable.
- Remove(): This method is used to remove elements from the specified key.
Example: This example demonstrates how to create a Hashtable, add key-value pairs and clear all the elements from the Hashtable.
C#
// Remove Elements from Hashtable
using System;
using System.Collections;
class Geeks {
// Main Method
static public void Main()
{
// Create a hashtable
// Using Hashtable class
Hashtable h1 = new Hashtable();
// Adding key/value pair
// in the hashtable
// Using Add() method
h1.Add("1", "Welcome");
h1.Add("2", "to");
h1.Add("3", "GeeksforGeeks");
// Using remove method
// remove A2 key/value pair
h1.Remove("2");
Console.WriteLine("Key and Value pairs :");
foreach(DictionaryEntry e1 in h1)
{
Console.WriteLine("{0} and {1} ", e1.Key,
e1.Value);
}
// Before using Clear method
Console.WriteLine("Total number of elements present"
+ " in h1:{0}",
h1.Count);
h1.Clear();
// After using Clear method
Console.WriteLine(
"Total number of elements present in"
+ " h1:{0}",
h1.Count);
}
}
OutputKey and Value pairs :
3 and GeeksforGeeks
1 and Welcome
Total number of elements present in h1:2
Total number of elements present in h1:0
3. Checking the Availability of Elements in the Hashtable: Hashtable class provides three methods to check if the element is present in the hashtable or not.
- Contains(): This method is used to check if a specific key or value exists in the Hashtable.
- ContainsKey(): This method is used to check if the specified key exists in the HashTable.
- ContainsValue(): This method is used to check if a specified value exists in the Hashtable.
Example: This example demonstrates how to check the presence of a key or value in a Hashtable using the Contains(), ContainsKey() and ContainsValue() method.
C#
// C# program to illustrate how
// to check key/value present
// in the hashtable or not
using System;
using System.Collections;
class Geeks {
// Main Method
static public void Main()
{
// Create a hashtable
// Using Hashtable class
Hashtable ht = new Hashtable();
// Adding key/value pair in the hashtable
// Using Add() method
ht.Add("1", "Welcome");
ht.Add("2", "to");
ht.Add("3", "GeeksforGeeks");
// Determine whether the given
// key present or not
// using Contains method
Console.WriteLine(ht.Contains("3"));
Console.WriteLine(ht.Contains(12));
Console.WriteLine();
// Determine whether the given
// key present or not
// using ContainsKey method
Console.WriteLine(ht.ContainsKey("1"));
Console.WriteLine(ht.ContainsKey(1));
Console.WriteLine();
// Determine whether the given
// value present or not
// using ContainsValue method
Console.WriteLine(ht.ContainsValue("geeks"));
Console.WriteLine(ht.ContainsValue("to"));
}
}
OutputTrue
False
True
False
False
True
4. Updating the Hashtable: In C#, the Hashtable class does not provide a direct method to update the value of an existing key. But we can achieve the update by following these steps:
- Check if the key exists in the Hashtable using the ContainsKey method.
- If the key exists, retrieve the current value using the key and store it in a variable.
- Assign the new value to the key in the Hash table using the same key.
- Optionally, remove the old key/value pair if needed.
Example: This example demonstrates how to update the value of an existing key in a Hashtable and print the updated key-value pairs.
C#
// C# Program to demonstrates how to update the hashtable
using System;
using System.Collections;
class Geeks {
static void Main()
{
// Create a new Hashtable
Hashtable ht = new Hashtable();
// Add some key-value pairs
ht.Add("key1", "value1");
ht.Add("key2", "value2");
// Updating the value of an existing key
string s = "key1";
if (ht.ContainsKey(s)) {
ht[s] = "s1";
}
// Accessing the updated value
string s1 = (string)ht[s];
Console.WriteLine("Updated value: " + s1);
// Print all key-value pairs in the ht
foreach(DictionaryEntry e in ht)
{
Console.WriteLine("Key: " + e.Key
+ ", Value: " + e.Value);
}
}
}
OutputUpdated value: s1
Key: key1, Value: s1
Key: key2, Value: value2
Similar Reads
Introduction
C# TutorialC# (pronounced "C-sharp") is a modern, versatile, object-oriented programming language developed by Microsoft in 2000 that runs on the .NET Framework. Whether you're creating Windows applications, diving into Unity game development, or working on enterprise solutions, C# is one of the top choices fo
4 min read
Introduction to .NET FrameworkThe .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The .NET framework is primarily used on Windows, while .NET Core (which evolved into
6 min read
C# .NET Framework (Basic Architecture and Component Stack)C# (C-Sharp) is a modern, object-oriented programming language developed by Microsoft in 2000. It is a part of the .NET ecosystem and is widely used for building desktop, web, mobile, cloud, and enterprise applications. This is originally tied to the .NET Framework, C# has evolved to be the primary
6 min read
C# Hello WorldThe Hello World Program is the most basic program when we dive into a new programming language. This simply prints "Hello World!" on the console. In C#, a basic program consists of the following:A Namespace DeclarationClass Declaration & DefinitionClass Members(like variables, methods, etc.)Main
4 min read
Common Language Runtime (CLR) in C#The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that manages the execution of .NET applications. It is responsible for loading and executing the code written in various .NET programming languages, including C#, VB.NET, F#, and others.When a C# program is compiled, th
4 min read
Fundamentals
C# IdentifiersIn programming languages, identifiers are used for identification purposes. Or in other words, identifiers are the user-defined name of the program components. In C#, an identifier can be a class name, method name, variable name, or label. Example: public class GFG { static public void Main () { int
2 min read
C# Data TypesData types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C# each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given pr
7 min read
C# VariablesIn C#, variables are containers used to store data values during program execution. So basically, a Variable is a placeholder of the information which can be changed at runtime. And variables allows to Retrieve and Manipulate the stored information. In Brief Defination: When a user enters a new valu
4 min read
C# LiteralsIn C#, a literal is a fixed value used in a program. These values are directly written into the code and can be used by variables. A literal can be an integer, floating-point number, string, character, boolean, or even null. Example:// Here 100 is a constant/literal.int x = 100; Types of Literals in
5 min read
C# OperatorsIn C#, Operators are special types of symbols which perform operations on variables or values. It is a fundamental part of language which plays an important role in performing different mathematical operations. It takes one or more operands and performs operations to produce a result.Types of Operat
7 min read
C# KeywordsKeywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to be used as variable names or objects. Doing this will result in a compile-time error.Example:C#// C# Program to illustrate the
5 min read
Control Statements
C# Decision Making (if, if-else, if-else-if ladder, nested if, switch, nested switch)Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of program based on certain conditions. These
5 min read
C# Switch StatementIn C#, Switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value of the expression. The switch expression is of integer type such as int, char, byte, or short, or of an enumeration type, or of string type.
4 min read
C# LoopsLooping in a programming language is a way to execute a statement or a set of statements multiple times, depending on the result of the condition to be evaluated to execute statements. The result condition should be true to execute statements within loops.Types of Loops in C#Loops are mainly divided
4 min read
C# Jump Statements (Break, Continue, Goto, Return and Throw)In C#, Jump statements are used to transfer control from one point to another point in the program due to some specified code while executing the program. In, this article, we will learn to different jump statements available to work in C#.Types of Jump StatementsThere are mainly five keywords in th
4 min read
OOP Concepts
Methods
Arrays
C# ArraysAn array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array spe
8 min read
C# Jagged ArraysA jagged array is an array of arrays, where each element in the main array can have a different length. In simpler terms, a jagged array is an array whose elements are themselves arrays. These inner arrays can have different lengths. Can also be mixed with multidimensional arrays. The number of rows
4 min read
C# Array ClassArray class in C# is part of the System namespace and provides methods for creating, searching, and sorting arrays. The Array class is not part of the System.Collections namespace, but it is still considered as a collection because it is based on the IList interface. The Array class is the base clas
7 min read
How to Sort an Array in C# | Array.Sort() Method Set - 1Array.Sort Method in C# is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method as follows:Sort<T>(T[]) MethodSort<T>(T[], IComparer<T>) MethodSort<T>(T[], Int32, Int32) MethodSort<T>(T[], Comparison<T>) Method
8 min read
How to find the rank of an array in C#Array.Rank Property is used to get the rank of the Array. Rank is the number of dimensions of an array. For example, 1-D array returns 1, a 2-D array returns 2, and so on. Syntax: public int Rank { get; } Property Value: It returns the rank (number of dimensions) of the Array of type System.Int32. B
2 min read
ArrayList
String
Tuple
Indexers