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:
- ArgumentNullException: If the key is null.
- NotSupportedException: If the property is set and the Hashtable is read-only. Or the property is set, key does not exist in the collection, and the Hashtable has a fixed size.
Note:
- This property returns the value associated with the specific key. If that key is not found, and one is trying to get that, then this property will return null and if trying to set, it will result into the creation of a new element with the specified key.
- Retrieving and setting the value of this property is an O(1) operation.
Below programs illustrate the use of above-discussed property:
Example 1:
using System;
using System.Collections;
class GFG {
public static void Main()
{
Hashtable myTable = new Hashtable();
myTable.Add( "g" , "geeks" );
myTable.Add( "c" , "c++" );
myTable.Add( "d" , "data structures" );
myTable.Add( "q" , "quiz" );
ICollection c = myTable.Keys;
foreach ( string str in c)
Console.WriteLine(str + ": " + myTable[str]);
myTable[ "c" ] = "C#" ;
Console.WriteLine( "Updated Values:" );
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:
using System;
using System.Collections;
class GFG {
public static void Main()
{
Hashtable myTable = new Hashtable();
myTable.Add( "4" , "Even" );
myTable.Add( "9" , "Odd" );
myTable.Add( "5" , "Odd and Prime" );
myTable.Add( "2" , "Even and Prime" );
ICollection c = myTable.Keys;
foreach ( string str in c)
Console.WriteLine(str + ": " + myTable[str]);
myTable[ "56" ] = "New Value" ;
Console.WriteLine( "Updated Values:" );
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:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
01 Feb, 2019
Like Article
Save Article