C# | Get or Set the value associated with specified key in Hashtable (original) (raw)

Last Updated : 01 Feb, 2019

Hashtable.Item[Object] Property is used to get or set the value associated with the specified key in the Hashtable.Syntax:

public virtual object this[object key] { get; set; }

Here, key is key of object type whose value is to get or set.Exceptions:

Note:

Below programs illustrate the use of above-discussed property:Example 1:

CSharp `

// C# code to Gets or sets the value // associated with the specified key 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]);

    // Setting the value associated with key "c"
    myTable["c"] = "C#";

    Console.WriteLine("Updated Values:");

    // Displaying the contents
    foreach(string str in c)
        Console.WriteLine(str + ": " + myTable[str]);
}

}

`

Output:

d: data structures c: c++ q: quiz g: geeks Updated Values: d: data structures c: C# q: quiz g: geeks

Example 2:

CSharp `

// C# code to Gets or sets the value // associated with the specified key 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]);

    // Setting the value associated
    // with key "56" which is not present 
    // will result in the creation of 
    // new key and value will be set which 
    // is given by the user
    myTable["56"] = "New Value";

    Console.WriteLine("Updated Values:");

    // 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: Even Updated Values: 5: Odd and Prime 9: Odd 2: Even and Prime 56: New Value 4: Even

Reference: