Add elements to a Hashtable

In this chapter you will learn:

  1. How to add elements to a Hashtable
  2. How to add to Hashtable with indexer

Adding to Hashtable

The following code uses Add method to add elements to the Hashtable and uses the Keys to obtain the values.

using System; /*j  a  v  a 2  s .  c om*/
using System.Collections; 
 
class HashtableDemo { 
  public static void Main() { 
    Hashtable ht = new Hashtable(); 
     
    
    ht.Add("a", "A"); 
    ht.Add("b", "B"); 
    ht.Add("c", "C"); 
    ht.Add("e", "E"); 
 
    // Get a collection of the keys. 
    ICollection c = ht.Keys; 
 
    foreach(string str in c) 
      Console.WriteLine(str + ": " + ht[str]); 
  } 
}

The code above generates the following result.

Adding with indexer

Other than using Add method to add key and value pair to a Hashtable we can also add key-value pair to Hashtable by using the indexer.

using System; /* j  a v a 2 s. c  om*/
using System.Collections; 
 
class HashtableDemo { 
  public static void Main() { 
    Hashtable ht = new Hashtable(); 
     
    
    ht.Add("a", "A"); 
    ht.Add("b", "B"); 
    ht.Add("c", "C"); 
    ht.Add("e", "E"); 

    
    ht["f"] = "F"; 
 
    // Get a collection of the keys. 
    ICollection c = ht.Keys; 
 
    foreach(string str in c) 
      Console.WriteLine(str + ": " + ht[str]); 
  } 
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to check if a key is contained in Hashtable
Home » C# Tutorial » Collections
HashSet
Set operation: Except
Set operator intersect
Remove with condition
HashSet contains
HashSet creation
HashSet removing element
Sub set operations
Hashtable
Hashtable ContainsValue
Add elements to a Hashtable
Hashtable containsKey
Remove from Hashtable
Hashtable to array
Queue
Generic Queue
Stack