Overview
Today, we will see, how hashtables work in C#. Hashtables are nothing but the collection of the key-value pairs. We will see in detail in this blog, so let's start .
Introduction
Hashtable is a collection of the Key-Value pairs, which are organized on the hash code of their respective keys.
When you add an element, it gets added to the hashtable and its corresponding hash code is generated automatically. Here, we are using the keys to access those hashcodes. Hashtable optimizes lookup with the help of the keys.
Syntax
Now, we had created a constructor, using its default constructor.
- Hashtable at=new Hashtable();
- at.Add(“1”,”Value”);
Now, you have to use for each loop to display the elements.
For retrieving the elements through the hashtable, use Dictionary Entry.
- foreach(DictionaryEntry e in ht)
- {
- Console.WriteLine(“{
- 0
- }, {
- 1
- }”, e.Key, e.Value);
- }
- ht.ContainsKey(1);
- int value = (int) ht[“One”];
Properties of Hashtable
- Keys: Gets an ICollection, which contains the keys in the Hashtable.
- Values: Gets an ICollection, which contains the values in the Hashtable.
Casting in Hashtable
We can use the ‘as’ operator to attempt to cast an object to a specific reference type. It returns true or false and you also reduce casting by using the ‘is’ operator.
If you want to store the keys in an array list: For storing the keys in an array list, you can use the keys property of Hashtable. For example,

Jiyaul MustaphaPosted Aug 8, 2019, 5:54 AM
DECLARE @SEPERATOR as VARCHAR(1) DECLARE @SP INT DECLARE @VALUE VARCHAR(MAX) SET @SEPERATOR = ',' CREATE TABLE #TempCode (id int NOT NULL) /**this Region For Storing SiteCode**/ WHILE PATINDEX('%' + @SEPERATOR + '%', @Code ) <> 0 BEGIN SELECT @SP = PATINDEX('%' + @SEPERATOR + '%' ,@Code) SELECT @VALUE = LEFT(@Code , @SP - 1) SELECT @Code = STUFF(Code, 1, @SP, '') INSERT INTO #TempCode (id) VALUES (@VALUE) END
Ajay KadianPosted May 8, 2018, 3:35 PM
Have you tried for checking the key value of your example? Like Console.WriteLine("Is contains : " + ht.ContainsKey(1)); It always return false. And adding should be ht.Add( 1 ,"Tom"); not ht.Add( "1" ,"Tom");
SubashPosted Oct 23, 2016, 9:38 PM
Nice share sir
Raja TPosted Aug 7, 2016, 6:15 AM
Good..