Hashtable class in C# is a part of the operations. It represents a collection of key-value pairs that are organized based on the hash code of the key. The Hashtable class provides various types of methods that are used to perform different types of operations on the hashtables. In Hashtable, keys are used to access the elements present in the collection. For very large Hashtable objects, we can increase the maximum capacity to 2 billion elements on a 64-bit system.
- In Hashtable, a key cannot be null but the value can be.
- In Hashtable, key objects must be immutable as long as they are used as keys in the Hashtable.
- The capacity of a Hashtable is the number of elements that Hashtable can hold.
- A hash function is provided by each key object in the Hashtable.
Example: This example demonstrates how to create a Hashtable, add key-value pairs, and display the elements.
C#
// C# Program to demonstrates Hashtable
using System;
using System.Collections;
class Geeks {
static void Main()
{
// Create a Hashtable of string
// keys and integer values
Hashtable ht = new Hashtable();
// Adding elements to the Hashtable
ht.Add("One", 1);
ht.Add("Two", 2);
ht.Add("Three", 3);
Console.WriteLine("Hashtable Elements:");
foreach(DictionaryEntry i in ht)
{
Console.WriteLine($"{i.Key}: {i.Value}");
}
}
}
OutputHashtable Elements:
Two: 2
Three: 3
One: 1
Declaration of Hashtable
In C#, the Hashtable is declared as:
Hashtable ht = new Hashtable();
Constructors
Constructor | Description |
---|
Hashtable() | Initalizes a new, empty instance with default parameters (initial capacity, load factor, etc.). |
Hashtable(IDictionary) | Copies elements from the specified dictionary to a new Hashtable with default parameters |
Hashtable(IDictionary, IEqualityComparer) | Copies elements from the specified dictionary to a new Hashtable and uses the provided IEqualityComparer |
Hashtable(Int32) | Initializes a new, empty instance with a specified initial capacity and default parameters. |
Hashtable(Int32, Single) | Initializes a new, empty instance with a specified initial capacity and load factor. |
Hashtable(Int32, Single, IEqualityComparer) | Initializes a new, empty instance with a specified initial capacity, load factor, and IEqualityComparer |
Hashtable(SerializationInfo, StreamingContext) | Initalizes a new instance from serialized data (for deserialization purposes). |
Example: This example demonstrates how to create and initialize two Hashtable objects, insert key-value pairs and print the mappings.
C#
// Using Hashtable() Constructor
using System;
using System.Collections;
class Geeks {
static void Main()
{
// Initialize Hashtable
Hashtable ht1 = new Hashtable();
Hashtable ht2 = new Hashtable();
// Inserting elements using Add() method
ht1.Add(1, "one");
ht1.Add(2, "two");
ht1.Add(3, "three");
ht2.Add(4, "four");
ht2.Add(5, "five");
ht2.Add(6, "six");
// Print mappings to the console
Console.WriteLine("Mappings of ht1: ");
foreach(DictionaryEntry i in ht1)
{
Console.WriteLine($"{i.Key} - {i.Value}");
}
Console.WriteLine("Mappings of ht2: ");
foreach(DictionaryEntry i in ht2)
{
Console.WriteLine($"{i.Key} - {i.Value}");
}
}
}
OutputMappings of ht1:
3 - three
2 - two
1 - one
Mappings of ht2:
6 - six
5 - five
4 - four
Properties
Properties | Description |
---|
comparer | Gets or sets the IComparer to use for the Hashtable. |
Count | Gets the number of key/value pairs contained in the Hashtable. |
EqualityComparer | Gets the IEqualityComparer to use for the Hashtable. |
hcp | Gets or sets the object that can dispense hash codes. |
IsFixedSize | Gets a value indicating whether the Hashtable has a fixed size. |
IsReadOnly | Gets a value indicating whether the Hashtable is read-only. |
IsSynchronized | Gets a value indicating whether access to the Hashtable is synchronized (thread safe). |
Item[Object] | Gets or sets the value associated with the specified key. |
Keys | Gets an ICollection containing the keys in the Hashtable. |
SyncRoot | Gets an object that can be used to synchronize access to the Hashtable. |
Values | Gets an ICollection containing the values in the Hashtable. |
Example: This example demonstrates how to use the IsSynchronized property check if a Hashtable is thread-safe and the Count property to get the number of elements in a Hashtable.
C#
// C# program to demonstrates the use
// of IsSynchronized and Count property
using System;
using System.Collections;
class Geeks {
static void Main(string[] args)
{
// create and initialize Hashtable using Add() method
Hashtable h1 = new Hashtable();
h1.Add("1", "Welcome");
h1.Add("2", "to");
h1.Add("3", "geeks");
h1.Add("4", "for");
h1.Add("5", "geeks");
// Creating a synchronized packing around the Hashtable
Hashtable h2 = Hashtable.Synchronized(h1);
// print the status of both Hashtables
Console.WriteLine("h1 Hashtable is {0}.",
h1.IsSynchronized ? "synchronized" : "not synchronized");
Console.WriteLine("h2 Hashtable is {0}.",
h2.IsSynchronized ? "synchronized" : "not synchronized");
// Using Count Property
Console.WriteLine("Total Number of Elements in h1: " + h1.Count);
}
}
Outputh1 Hashtable is not synchronized.
h2 Hashtable is synchronized.
Total Number of Elements in h1: 5
Methods
Method | Description |
---|
Add(Object, Object) | Adds an element with the specified key and value into the Hashtable. |
Clear() | Removes all elements from the Hashtable. |
Clone() | Creates a shallow copy of the Hashtable. |
Contains(Object) | Determines whether the Hashtable contains a specific key. |
ContainsKey(Object) | Determines whether the Hashtable contains a specific key. |
ContainsValue(Object) | Determines whether the Hashtable contains a specific value. |
CopyTo(Array, Int32) | Copies the Hashtable elements to a one-dimensional Array instance at the specified index. |
Equals(Object) | Determines whether the specified object is equal to the current object. |
GetEnumerator() | Returns an IDictionaryEnumerator that iterates through the Hashtable. |
GetHashCode() | Serves as the default hash function. |
GetObjectData(SerializationInfo, StreamingContext) | Implements the ISerializable interface and returns the data needed to serialize the Hashtable. |
GetType() | Gets the Type of the current instance. |
Remove(Object) | Removes the element with the specified key from the Hashtable. |
Synchronized(Hashtable) | Returns a synchronized (thread-safe) wrapper for the Hashtable. |
ToString() | Returns a string that represents the current object. |
Example:
C#
// C# program to demonstrate the working of Add()
// and Remove() Methods
using System;
using System.Collections;
class Geeks {
static void Main(string[] args)
{
// create and initialize Hash table
// using Add() method
Hashtable ht = new Hashtable();
ht.Add("1", "Geek1");
ht.Add("2", "Geek2");
ht.Add("3", "Geek3");
ht.Add("4", "Geek4");
ht.Add("5", "Geek5");
ICollection k = ht.Keys;
Console.WriteLine("Hashtable Contains:");
foreach(var i in k)
{
Console.WriteLine(i + "-" + ht[i]);
}
Console.WriteLine();
// Remove element 4
// using Remove() method
ht.Remove("4");
ht.Remove("5");
// printing updated Hash table
Console.WriteLine("Hashtable after removing element 4:");
foreach(var i in k)
{
Console.WriteLine(i + "-" + ht[i]);
}
}
}
OutputHashtable Contains:
3-Geek3
5-Geek5
4-Geek4
2-Geek2
1-Geek1
Hashtable after removing element 4:
3-Geek3
2-Geek2
1-Geek1
Similar Reads
C# Tutorial C# (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 Framework The .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# Interview Questions and Answers C# is the most popular general-purpose programming language and was developed by Microsoft in 2000, renowned for its robustness, flexibility, and extensive application range. It is simple and has an object-oriented programming concept that can be used for creating different types of applications.Her
15+ min read
C# Dictionary Dictionary in C# is a generic collection that stores key-value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of a Dictionary is, that it is a generic type. A dictionary is defined under System.Collections.Generic namespace. It is dynamic in nature mean
5 min read
C# List Class In C#, the List<T> class represents the list of objects that can be accessed by index. It comes under the System.Collections.Generic namespace. List class can be used to create a collection of different types like integers, strings, etc. List<T> class also provides the methods to search,
7 min read
C# Delegates A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. It provides a way which tells which method is to be called when an event is triggered. For example, if you click on a Button on a form (Windows Form application),
6 min read
ASP.NET Interview Questions and Answer ASP.NET is a popular framework by Microsoft for building fast and scalable web applications. It allows developers to create dynamic websites, services, and apps, using server-side code and offering a user-friendly experience. Trusted by companies like Microsoft, Dell, and Accenture, ASP.NET is used
15+ 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# Data Types Data 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# Arrays An 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