C# Hashtable

In C#, a Hashtable is a non-generic collection that is used to store key-value pairs. It is similar to a dictionary, but is not strongly typed and does not have the generic type safety of the Dictionary<TKey, TValue> class.

A Hashtable can store keys and values of any data type, but it is slower than a dictionary for most operations. It is useful when you need to store a large amount of data and are not concerned about type safety.

Here's an example of how to create and use a Hashtable in C#:

// Creating a hashtable
Hashtable myHashtable = new Hashtable();

// Adding entries to the hashtable
myHashtable.Add("apple", 1);
myHashtable.Add("banana", 2);
myHashtable.Add("cherry", 3);

// Accessing the value associated with a key
int value = (int)myHashtable["banana"];
Console.WriteLine(value);  // Output: 2

// Modifying the value associated with a key
myHashtable["cherry"] = 4;

// Removing an entry from the hashtable
myHashtable.Remove("apple");

// Iterating over the entries in the hashtable
foreach (DictionaryEntry entry in myHashtable)
{
    Console.WriteLine(entry.Key + ": " + entry.Value);
}
Sourc‮gi.www:e‬iftidea.com

This would output:

banana: 2
cherry: 4

Note that we need to cast the value associated with a key to the appropriate data type when retrieving it from the hashtable, as it is stored as an object.