Last Updated : 11 Jul, 2025
The Hashtable class represents a collection of
key-and-value pairsthat 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) Methodis used to adds an element with the specified key and value into the Hashtable.
Syntax:public virtual void Add(object key, object value);Parameters:
key: It is the specified key of the element to add of type System.Object. value: It is the specified value of the element to add of type System.Object. The value can be null.Exceptions:
Below given are some examples to understand the implementation in a better way :
Example 1 : CSHARP
// C# code for adding an element with the
// specified key and value into the Hashtable
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating a Hashtable
Hashtable myTable = new Hashtable();
// Adding elements in Hashtable
myTable.Add("g", "geeks");
myTable.Add("c", "c++");
myTable.Add("d", "data structures");
myTable.Add("q", "quiz");
// Get a collection of the keys.
ICollection c = myTable.Keys;
// Displaying the contents
foreach(string str in c)
Console.WriteLine(str + ": " + myTable[str]);
}
}
Output:
d: data structures c: c++ q: quiz g: geeksExample 2: CSHARP
// C# code for adding an element with the
// specified key and value into the Hashtable
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating a Hashtable
Hashtable myTable = new Hashtable();
// Adding elements in Hashtable
myTable.Add("4", "Even");
myTable.Add("9", "Odd");
myTable.Add("5", "Odd and Prime");
myTable.Add("2", "Even and Prime");
// Get a collection of the keys.
ICollection c = myTable.Keys;
// Displaying the contents
foreach(string str in c)
Console.WriteLine(str + ": " + myTable[str]);
}
}
Output:
5: Odd and Prime 9: Odd 2: Even and Prime 4: EvenReference:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4