C# | Gets or sets the value at the specified key in StringDictionary
Last Updated :
01 Feb, 2019
StringDictionary.Item[String] Property is used to get or set the value associated with the specified key.
Syntax:
public virtual string this[string key] { get; set; }
Here, key is the Key of type System.String whose value is be to get or set.
Return Value: This property returns the value associated with the specified key. If the specified key is not found, Get returns null, and Set creates a new entry with the specified key.
Exception: This property throws ArgumentNullException
if the key is null.
Below programs illustrate the use of above-discussed property:
Example 1:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
StringDictionary my1 = new StringDictionary();
my1.Add( "1" , "C" );
my1.Add( "2" , "C++" );
my1.Add( "3" , "Java" );
my1.Add( "4" , "Python" );
my1.Add( "5" , "C#" );
foreach (DictionaryEntry d in my1)
{
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine( "\nAfter Item[String] Property: \n" );
my1[ "2" ] = "HTML" ;
foreach (DictionaryEntry d1 in my1)
{
Console.WriteLine(d1.Key + " " + d1.Value);
}
}
}
|
Output:
3 Java
5 C#
4 Python
2 C++
1 C
After Item[String] Property:
3 Java
4 Python
2 HTML
1 C
5 C#
Example 2:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
StringDictionary my1 = new StringDictionary();
my1.Add( "1" , "HTML" );
my1.Add( "2" , "CSS" );
my1.Add( "3" , "PHP" );
my1.Add( "4" , "MongoDB" );
my1.Add( "5" , "AngularJS" );
foreach (DictionaryEntry d in my1)
{
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine( "\nAfter Item[String] Property: \n" );
my1[ "8" ] = "C#" ;
foreach (DictionaryEntry d1 in my1)
{
Console.WriteLine(d1.Key + " " + d1.Value);
}
}
}
|
Output:
3 PHP
5 AngularJS
4 MongoDB
2 CSS
1 HTML
After Item[String] Property:
3 PHP
4 MongoDB
2 CSS
1 HTML
8 C#
5 AngularJS
Reference:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...