C# Hashtable with Examples - GeeksforGeeks (2024)

Last Updated : 08 Mar, 2024

Summarize

Comments

Improve

Suggest changes

Like Article

Like

Save

Report

A Hashtable is a collection of key/value pairs that are arranged based on the hash code of the key. In other words, a Hashtable is used to create a collection that uses a hash table for storage. It generally optimizes the lookup by calculating the hash code of every key and storing it into another basket automatically and when you access the value from the hashtable at that time it matches the hashcode with the specified key. It is the non-generic type of collection that is defined in the System. Collections namespace.

Important Points:

  • In Hashtable, the 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.
  • The Hashtable class implements the IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, and ICloneable interfaces.
  • In the hashtable, you can store elements of the same type and of the different types.
  • The elements of the hashtable that is a key/value pair are stored in DictionaryEntry, so you can also cast the key/value pairs to a DictionaryEntry.
  • that key that must be unique. Duplicate keys are not allowed.

How to create a Hashtable?

The Hashtable class provides 16 different types of constructors that are used to create a hashtable, here we only use Hashtable() constructor. To read more about Hashtable’s constructors you can refer to C# | Hashtable Class 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 comparer. Now, let’s see how to create a hashtable using Hashtable() constructor:

Step 1: Include System. Collections namespace in your program with the help of using keyword:

using System.Collections;

Step 2: Create a hashtable using Hashtable class as shown below:

Hashtable hashtable_name = new Hashtable();

Step 3: If you want to add a key/value pair in your hashtable, then use Add() method to add elements in your hashtable. And you can also store a key/value pair in your hashtable without using Add() method.

Example:

C#

// C# program to illustrate how

// to create a hashtable

using System;

using System.Collections;

class GFG {

// Main Method

static public void Main()

{

// Create a hashtable

// Using Hashtable class

Hashtable my_hashtable1 = new Hashtable();

// Adding key/value pair

// in the hashtable

// Using Add() method

my_hashtable1.Add("A1", "Welcome");

my_hashtable1.Add("A2", "to");

my_hashtable1.Add("A3", "GeeksforGeeks");

Console.WriteLine("Key and Value pairs from my_hashtable1:");

foreach(DictionaryEntry ele1 in my_hashtable1)

{

Console.WriteLine("{0} and {1} ", ele1.Key, ele1.Value);

}

// Create another hashtable

// Using Hashtable class

// and adding key/value pairs

// without using Add method

Hashtable my_hashtable2 = new Hashtable() {

{1, "hello"},

{2, 234},

{3, 230.45},

{4, null}};

Console.WriteLine("Key and Value pairs from my_hashtable2:");

foreach(var ele2 in my_hashtable2.Keys)

{

Console.WriteLine("{0}and {1}", ele2,

my_hashtable2[ele2]);

}

}

}

Output

Key and Value pairs from my_hashtable1:A3 and GeeksforGeeks A2 and to A1 and Welcome Key and Value pairs from my_hashtable2:4and 3and 230.452and 2341and hello

How to remove elements from the hashtable?

In Hashtable, you are allowed to remove elements from the hashtable. The Hashtable class provides two different methods to remove elements and the methods are:

  • Clear : This method is used to remove all the objects from the hashtable.
  • Remove : This method is used to remove the element with the specified key from the hashtable.

Example:

C#

// C# program to illustrate how

// remove elements from the hashtable

using System;

using System.Collections;

class GFG {

// Main Method

static public void Main()

{

// Create a hashtable

// Using Hashtable class

Hashtable my_hashtable = new Hashtable();

// Adding key/value pair

// in the hashtable

// Using Add() method

my_hashtable.Add("A1", "Welcome");

my_hashtable.Add("A2", "to");

my_hashtable.Add("A3", "GeeksforGeeks");

// Using remove method

// remove A2 key/value pair

my_hashtable.Remove("A2");

Console.WriteLine("Key and Value pairs :");

foreach(DictionaryEntry ele1 in my_hashtable)

{

Console.WriteLine("{0} and {1} ", ele1.Key, ele1.Value);

}

// Before using Clear method

Console.WriteLine("Total number of elements present"+

" in my_hashtable:{0}", my_hashtable.Count);

my_hashtable.Clear();

// After using Clear method

Console.WriteLine("Total number of elements present in"+

" my_hashtable:{0}", my_hashtable.Count);

}

}

Output

Key and Value pairs :A3 and GeeksforGeeks A1 and Welcome Total number of elements present in my_hashtable:2Total number of elements present in my_hashtable:0

How to check the availability of key/value pair in hashtable?

In hashtable, you can check whether the given pair is present or not using the following methods:

  • Contains: This method is used to check whether the Hashtable contains a specific key.
  • ContainsKey: This method is also used to check whether the Hashtable contains a specific key.
  • ContainsValue: This method is used to check whether the Hashtable contains a specific value.

Example:

C#

// C# program to illustrate how

// to check key/value present

// in the hashtable or not

using System;

using System.Collections;

class GFG {

// Main Method

static public void Main()

{

// Create a hashtable

// Using Hashtable class

Hashtable my_hashtable = new Hashtable();

// Adding key/value pair in the hashtable

// Using Add() method

my_hashtable.Add("A1", "Welcome");

my_hashtable.Add("A2", "to");

my_hashtable.Add("A3", "GeeksforGeeks");

// Determine whether the given

// key present or not

// using Contains method

Console.WriteLine(my_hashtable.Contains("A3"));

Console.WriteLine(my_hashtable.Contains(12));

Console.WriteLine();

// Determine whether the given

// key present or not

// using ContainsKey method

Console.WriteLine(my_hashtable.ContainsKey("A1"));

Console.WriteLine(my_hashtable.ContainsKey(1));

Console.WriteLine();

// Determine whether the given

// value present or not

// using ContainsValue method

Console.WriteLine(my_hashtable.ContainsValue("geeks"));

Console.WriteLine(my_hashtable.ContainsValue("to"));

}

}

Output

TrueFalseTrueFalseFalseTrue

How to update an Hash Table?

In C#, the Hashtable class does not provide a direct method to update the value of an existing key. However, you can achieve the update by following these steps:

  1. Check if the key exists in the Hashtable using the ContainsKey method.
  2. If the key exists, retrieve the current value using the key and store it in a variable.
  3. Assign the new value to the key in the Hash table using the same key.
  4. Optionally, remove the old key/value pair if needed.

Here’s an example that demonstrates how to update a value in a Hash table:

C#

using System;

using System.Collections;

class Program

{

static void Main()

{

// Create a new Hashtable

Hashtable hashtable = new Hashtable();

// Add some key-value pairs

hashtable.Add("key1", "value1");

hashtable.Add("key2", "value2");

// Updating the value of an existing key

string keyToUpdate = "key1";

if (hashtable.ContainsKey(keyToUpdate))

{

hashtable[keyToUpdate] = "updatedValue";

}

// Accessing the updated value

string updatedValue = (string)hashtable[keyToUpdate];

Console.WriteLine("Updated value: " + updatedValue);

// Print all key-value pairs in the hashtable

foreach (DictionaryEntry entry in hashtable)

{

Console.WriteLine("Key: " + entry.Key + ", Value: " + entry.Value);

}

}

}

Output

Updated value: updatedValueKey: key1, Value: updatedValueKey: key2, Value: value2


ankita_saini

C# Hashtable with Examples - GeeksforGeeks (3)

Improve

Previous Article

SortedDictionary Implementation in C#

Next Article

C# Stack with Examples

Please Login to comment...

Similar Reads

C# | Check if a Hashtable is equal to another Hashtable The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Syntax: myTable1.Equals(myTable2) Here, myTable1 and myTable2 are the two Hashtables which is to be checked. Below given are some examples to understand the implementation in 2 min read C# | Check if Hashtable has a fixed size Hashtable.IsFixedSize Property is used to get a value which indicates whether the Hashtable has a fixed size or not. Syntax: public virtual bool IsFixedSize { get; } Return Value: This property returns true if the Hashtable has a fixed size otherwise it returns false. The default is false. Below programs illustrate the above-discussed property: Exa 2 min read C# | Adding an element into the Hashtable The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Add(Object, Object) Method is used to adds an element with the specified key and value into the Hashtable. Syntax: public virtual void Add(object key, object value) 2 min read C# | Check if the Hashtable contains a specific Key The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.ContainsKey(Object) Method is used to check whether the Hashtable contains a specific key or not. Syntax: public virtual bool ContainsKey(object key); Parameter: ke 2 min read C# | Check if the Hashtable contains a specific Value The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.ContainsValue(Object) Method is used to check whether the Hashtable contains a specific value or not. Syntax: public virtual bool ContainsValue(object value); Param 2 min read C# | Remove the element with the specified key from the Hashtable The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Remove(Object) Method is used to remove the element with the specified key from the Hashtable. Syntax: public virtual void Remove (object key); Parameter: key: It i 2 min read C# | Remove all elements from the Hashtable The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Clear Method is used to remove all elements from the Hashtable. Syntax: myTable.Clear() Here myTable is the name of the Hashtable. Exceptions: This method will give 2 min read C# | Count the number of key/value pairs in the Hashtable The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Count Property is used to get the total number of the key/value pairs contained in the Hashtable. Syntax: myTable.Count Here, myTable is the name of the Hashtable. 2 min read C# | Get or Set the value associated with specified key in Hashtable Hashtable.Item[Object] Property is used to get or set the value associated with the specified key in the Hashtable. Syntax: public virtual object this[object key] { get; set; } Here, key is key of object type whose value is to get or set. Exceptions: ArgumentNullException: If the key is null. NotSupportedException: If the property is set and the Ha 3 min read C# | Gets an ICollection containing the keys in the Hashtable Hashtable.Keys Property is used to get an ICollection containing the keys in the Hashtable. Syntax: public virtual System.Collections.ICollection Keys { get; } Return Value: This property returns an ICollection containing the keys in the Hashtable. Note: The order of keys in the ICollection is unspecified. Retrieving the value of this property is a 2 min read C# | Gets an ICollection containing the values in the Hashtable Hashtable.Values Property is used to get an ICollection containing the values in the Hashtable. Syntax: public virtual System.Collections.ICollection Values { get; } Return Value: This property returns an ICollection containing the values in the Hashtable. Note: The order of values in the ICollection is unspecified. Retrieving the value of this pro 2 min read C# | Hashtable Class The Hashtable class represents a collection of key/value pairs that are organized based on the hash code of the key. This class comes under the System.Collections namespace. The Hashtable class provides various types of methods that are used to perform different types of operation on the hashtables. In Hashtable, keys are used to access the element 7 min read C# | Get an enumerator that iterates through the Hashtable Hashtable.GetEnumerator Method is used to returns an IDictionaryEnumerator that iterates through the Hashtable. Syntax: public virtual System.Collections.IDictionaryEnumerator GetEnumerator (); Return Value: It returns an IDictionaryEnumerator for the Hashtable. Below programs illustrate the use of Hashtable.GetEnumerator Method: Example 1: // C# c 2 min read C# | Copying the Hashtable elements to an Array Instance Hashtable.CopyTo(Array, Int32) Method is used to copy the elements of a Hashtable to a one-dimensional Array instance at the specified index.Syntax: public virtual void CopyTo (Array array, int arrayIndex); Parameters: array : The one-dimensional Array that is the destination of the DictionaryEntry objects copied from Hashtable. The Array must have 3 min read C# | Check whether a Hashtable contains a specific key or not Hashtable.Contains(Object) Method is used to check whether the Hashtable contains a specific key or not. Syntax: public virtual bool Contains (object key); Here, key is the Key of Object type which is to be located in the Hashtable. Return Value: This method returns true if the Hashtable contains an element with the specified key otherwise returns 2 min read C# | Check if Hashtable is read-only Hashtable.IsReadOnly property is used to get a value indicating whether the Hashtable is read-only or not. Syntax: public virtual bool IsReadOnly { get; } Return Value: This property returns true if the Hashtable is read-only otherwise it returns false. The default is false. Below programs illustrate the above-discussed property: Example 1: // C# c 2 min read C# | Check if Hashtable is synchronized (thread safe) Hashtable.IsSynchronized Property is used to get a value indicating whether access to the Hashtable is synchronized(thread-safe). Syntax: public virtual bool IsSynchronized { get; } Return Value: This property return true if access to the Hashtable is synchronized (thread-safe), otherwise it returns false. The default is false. Below programs illus 2 min read C# | How to get hash code for the specified key of a Hashtable Hashtable.GetHash(Object) method is used to get the hashcode of the specified key of a Hashtable object. This method is inherited from the Object Class. Syntax: protected virtual int GetHash(Object Key); Exception: This method will give NullReferenceException if the key is null. Below programs illustrate the use of above-discussed method: Example 1 2 min read C# | Creating a synchronized (thread-safe) wrapper for the Hashtable Hashtable.Synchronized(Hashtable) Method is used to return a synchronized (thread-safe) wrapper for the Hashtable.Syntax: public static System.Collections.Hashtable Synchronized (System.Collections.Hashtable table); Here table is the Hashtable which is to be synchronized.Return Value: This method returns a synchronized (thread-safe) wrapper for the 2 min read How to create a shallow copy of Hashtable in C# Hashtable.Clone Method is used to create a shallow copy of the Hashtable. When we make a shallow copy, only the elements of the collection get copied irrespective of its type, it doesn't copy the objects referred to by the references. Basically, it creates a new object and that object points to the original references. Syntax: HashtableName.Clone() 3 min read Difference between Hashtable and Dictionary in C# In C#, Dictionary is a generic collection which is generally used to store key/value pairs. Dictionary is defined under System.Collection.Generics namespace. It is dynamic in nature means the size of the dictionary is growing according to the need. Example: [GFGTABS] CSharp // C# program to illustrate Dictionary using System; using System.Collectio 3 min read Array.GetValue() Method in C# with Examples | Set - 1 Array.GetValue() Method in C# is used to gets the value of the specified element in the current Array. There are total 8 methods in the overload list of this method which are as follows: Array.GetValue(Int32, Int32) Array.GetValue(Int64, Int64) Array.GetValue(Int32) Array.GetValue(Int64) Array.GetValue(Int32, Int32, Int32) Array.GetValue(Int64, Int 4 min read File.GetLastWriteTimeUtc() Method in C# with Examples File.GetLastWriteTimeUtc(String) is an inbuilt File class method which is used to return the date and time, in coordinated universal time (UTC), that the specified file or directory was last written to.Syntax: public static DateTime GetLastWriteTimeUtc (string path); Parameter: This function accepts a parameter which is illustrated below: path: Thi 2 min read MathF.Sin() Method in C# with Examples MathF.Sin(Single) is an inbuilt MathF class method which returns the sine of a given float value argument(specified angle). Syntax: public static float Sin (float x); Here, x is the angle(measured in radian) whose sine is to be returned and the type of this parameter is System.Single. Return Value: This method will return the sine of x of type Syst 2 min read Double.CompareTo Method in C# with Examples Double.CompareTo Method is used to compare the current instance to a specified object or Double object. It will return an integer which shows whether the value of the current instance is greater than, less than or equal to the value of the specified object or Double object. There are 2 methods in the overload list of this method as follows: Compare 5 min read UInt64.MinValue Field in C# with Examples The MinValue property or Field of UInt64 Struct is used to represent the minimum possible value of the 64-bit unsigned long integer i.e. ulong data type. The value of this field is constant means that a user cannot change the value of this field. The value of this field is 0. This prevents an OverflowException at run time. Syntax: public const ulon 1 min read UInt16.GetHashCode Method in C# with Examples UInt16.GetHashCode method is used to get the HashCode for the current UInt16 instance. Syntax: public override int GetHashCode (); Return Value: This method returns a 32-bit signed integer hash code. Below programs illustrate the use of the above discussed-method: Example 1: // C# program to illustrate the // UInt16.GetHashCode() Method using Syste 1 min read Int64.CompareTo Method in C# with Examples Int64.CompareTo Method is used to compare the current instance to a specified object or Int64 and returns a sign of their relative values. There are 2 methods in the overload list of this method as follows: CompareTo(Int64) Method CompareTo(Object) Method Int64.CompareTo(Int64) Method This method is used to compare the current instance to a specifi 4 min read MathF.Truncate() Method in C# with Examples In C#, MathF.Truncate(Single) is a MathF class method which is used to compute an integral part of a specified single number or single-precision floating-point number.Syntax: public static float Truncate (float x); Parameter: x: It is the specified number which is to be truncated and type of this parameter is System.Single. Return Type: This method 1 min read MathF.Exp() Method in C# with Examples In C#, Exp(Single) is a MathF class method which is used to return the e raised to the specified power. Here e is a mathematical constant whose value is approximately 2.71828. Syntax: public static float Exp (float x); Here, x is the required number of type System.Single which specifies a power. Return Type: It returns a number e raised to the powe 1 min read

Article Tags :

  • C#
  • CSharp-Collections-Hashtable
  • CSharp-Collections-Namespace
C# Hashtable with Examples - GeeksforGeeks (2024)
Top Articles
Why Is My Poop So Big It Clogs The Toilet? Causes & Treatment
How Can You Track Instagram Traffic in Google Analytics?
Brgeneral Patient Portal
Mikayla Campinos Videos: A Deep Dive Into The Rising Star
Culver's Flavor Of The Day Monroe
LA Times Studios Partners With ABC News on Randall Emmett Doc Amid #Scandoval Controversy
13 The Musical Common Sense Media
Vichatter Gifs
Los Angeles Craigs List
Belly Dump Trailers For Sale On Craigslist
800-695-2780
Justified Official Series Trailer
Best Forensic Pathology Careers + Salary Outlook | HealthGrad
How to Watch the Fifty Shades Trilogy and Rom-Coms
Craigslist Appomattox Va
Yard Goats Score
Beryl forecast to become an 'extremely dangerous' Category 4 hurricane
Wsop Hunters Club
Fsga Golf
Www.dunkinbaskinrunsonyou.con
Gran Turismo Showtimes Near Marcus Renaissance Cinema
Xfinity Outage Map Fredericksburg Va
Naval Academy Baseball Roster
European Wax Center Toms River Reviews
Dashboard Unt
No Limit Telegram Channel
Stockton (California) – Travel guide at Wikivoyage
Yayo - RimWorld Wiki
Sacramento Craigslist Cars And Trucks - By Owner
Craftsman Yt3000 Oil Capacity
Craigslist Sf Garage Sales
Lawrence Ks Police Scanner
Abga Gestation Calculator
Springfield.craigslist
Omnistorm Necro Diablo 4
To Give A Guarantee Promise Figgerits
Eastern New Mexico News Obituaries
Daily Times-Advocate from Escondido, California
B.C. lightkeepers' jobs in jeopardy as coast guard plans to automate 2 stations
Craigslist Pets Plattsburgh Ny
Restored Republic June 6 2023
511Pa
All Obituaries | Sneath Strilchuk Funeral Services | Funeral Home Roblin Dauphin Ste Rose McCreary MB
Post A Bid Monticello Mn
Rage Of Harrogath Bugged
Csgold Uva
Premiumbukkake Tour
Workday Latech Edu
300+ Unique Hair Salon Names 2024
Diamond Desires Nyc
How To Find Reliable Health Information Online
Latest Posts
Article information

Author: Francesca Jacobs Ret

Last Updated:

Views: 6338

Rating: 4.8 / 5 (68 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Francesca Jacobs Ret

Birthday: 1996-12-09

Address: Apt. 141 1406 Mitch Summit, New Teganshire, UT 82655-0699

Phone: +2296092334654

Job: Technology Architect

Hobby: Snowboarding, Scouting, Foreign language learning, Dowsing, Baton twirling, Sculpting, Cabaret

Introduction: My name is Francesca Jacobs Ret, I am a innocent, super, beautiful, charming, lucky, gentle, clever person who loves writing and wants to share my knowledge and understanding with you.