C# Hashtable Tutorial For Beginners With Examples

A C# Hashtable represents a collection in which objects are stored and retrieved using a key.
Each key in a Hashtable has a hash code using which the objects in a Hashtable are organized.

Create a Hashtable in C#

A Hashtable can be created using the below code:
    Hashtable shoppingCart = new Hashtable();

Add items to a C# Hashtable

To add items to a Hashtable Add method is used. In the below example a key called as Camera with value 3 is added to the Hashtable shoppingCart.
     shoppingCart.Add("Camera", 3);     
        
Every item in a Hashtable has a unique key and an associated value. A Hashtable is a collection of such key/value pairs. Each of these items is a type of DictionaryEntry object.
Below three unique keys are added to a Hashtable. The key name and the associated value is then displayed using a foreach loop.
    Hashtable shoppingCart = new Hashtable();

    shoppingCart.Add("Camera", 3);
    shoppingCart.Add("Computer", 2);
    shoppingCart.Add("Trouser", 5);

    foreach (DictionaryEntry item in shoppingCart)
    {
        Console.WriteLine("Key " + item.Key + " has value " + item.Value);
    }
        
Output:
Key Computer has value 2
Key Trouser has value 5
Key Camera has value 3
Objects in a Hashtable can be null whereas the keys can't be.

Remove items from C# Hashtable

To remove items from a Hashtable Remove method is used. In the below example the keyCamera is removed from the Hashtable shoppingCart.
     shoppingCart.Remove("Camera", 3);     
        
Removing a key also removes the associated value from a Hashtable.

Methods and Properties of a C# Hashtable

Commonly used methods of a Hashtable are:
MethodDescription
AddAdds an item with a specific key and value to the Hashtable.
ClearRemoves all items from the Hashtable.
ContainKeyChecks if a specific key is present in a Hashtable.
ContainsValueChecks if a specific value is present in a Hashtable.
GetHashGets the hash code associated with a key in a Hashtable.
RemoveRemoves a key and associated value from a Hashtable.
Commonly used properties of a Hashtable are:
PropertyDescription
CountReturns the number of items (Key/Value pairs) present in a Hashtable.
IsReadOnlyReturns a boolean value which specifies whether a Hashtable is readonly or not.
ItemRepresents a key/value pair in a Hashtable.
KeysReturns a collection of all the keys present in a Hashtable.
ValuesReturns a collection of all the values present in a Hashtable.

1 comment: