Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Add Items to Hashtable Collection in C#
A Hashtable collection in C# stores key-value pairs using a hash-based mechanism. Each key-value pair is organized based on the hash code of the key, which is calculated using a hash function. Unlike modern generic collections, hashtables can store objects of different data types but exhibit lower performance due to boxing and unboxing operations.
In this article, we will explore how to add items to a hashtable collection using various methods available in the Hashtable class.
Syntax
The primary method for adding items to a hashtable is the Add() method
public virtual void Add(object key, object value);
You can also add items using index notation
hashtable[key] = value;
Parameters
key The key of the element to add (type
object). Must be non-null and unique.value The value of the element to add (type
object). Can be null.
Exceptions
ArgumentNullException Thrown when the key is null.
ArgumentException Thrown when an element with the same key already exists.
NotSupportedException Thrown when the hashtable is read-only or has a fixed size.
Using Add() Method
The Add() method is the primary way to add key-value pairs to a hashtable
using System;
using System.Collections;
class Program {
static void Main(string[] args) {
Hashtable mixedHashTable = new Hashtable();
// Add method with different data types
mixedHashTable.Add("msg", "Collection");
mixedHashTable.Add("site", "HashTable");
mixedHashTable.Add(1, 3.14);
mixedHashTable.Add(2, null);
// Assign value using indexer
mixedHashTable[3] = "Tutorial";
// Demonstrate exception handling for duplicate keys
try {
mixedHashTable.Add(2, 750);
} catch {
Console.WriteLine("Hashtable already has an element with Key = '2'.");
}
Console.WriteLine("*********HashTable Elements********");
foreach (DictionaryEntry elem in mixedHashTable) {
Console.WriteLine("Key = {0}, Value = {1}", elem.Key, elem.Value);
}
}
}
The output of the above code is
Hashtable already has an element with Key = '2'. *********HashTable Elements******** Key = 2, Value = Key = msg, Value = Collection Key = 3, Value = Tutorial Key = site, Value = HashTable Key = 1, Value = 3.14
Using Index Notation
You can add items directly using the indexer syntax, which is more convenient for updating existing keys
using System;
using System.Collections;
class Program {
public static void Main() {
Hashtable strHashTable = new Hashtable();
// Adding elements using Add() method
strHashTable.Add("4", "Even Number");
strHashTable.Add("9", "Odd Number");
strHashTable.Add("5", "Odd and Prime Number");
strHashTable.Add("2", "Even and Prime Number");
// Adding using indexer (alternative method)
strHashTable["6"] = "Even Number";
// Get collection of keys
ICollection keys = strHashTable.Keys;
Console.WriteLine("=========Contents of the Hashtable=========");
foreach(string key in keys) {
Console.WriteLine(key + ": " + strHashTable[key]);
}
}
}
The output of the above code is
=========Contents of the Hashtable========= 6: Even Number 5: Odd and Prime Number 9: Odd Number 2: Even and Prime Number 4: Even Number
Add() vs Indexer Comparison
| Add() Method | Indexer [key] = value |
|---|---|
| Throws exception if key already exists | Overwrites existing value for duplicate keys |
| More explicit and safer for new additions | Convenient for both adding and updating |
| Better for ensuring unique keys | Better for flexible key-value assignment |
Key Rules
Keys must be non-null and unique within the hashtable.
Values can be null or any object type.
Hashtable supports mixed data types for both keys and values.
Use
Add()for strict key uniqueness, indexer for flexible assignment.
Conclusion
Adding items to a hashtable in C# can be accomplished using the Add() method for strict key enforcement or the indexer notation for flexible assignment. The hashtable's ability to store mixed data types makes it versatile, though modern generic collections like Dictionary<TKey, TValue> are generally preferred for better performance and type safety.
