Open In App

C# | Add key and value into StringDictionary

StringDictionary.Add(String, String) method is used to add an entry with the specified key and value into the StringDictionary.

Syntax:



public virtual void Add (string key, string value);

Parameters:

Exceptions:



Below programs illustrate the use of StringDictionary.Add(String, String) method:

Example 1:




// C# code to add key and value
// into the StringDictionary
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a StringDictionary named myDict
        StringDictionary myDict = new StringDictionary();
  
        // Adding key and value into the StringDictionary
        myDict.Add("A", "Apple");
        myDict.Add("B", "Banana");
        myDict.Add("C", "Cat");
        myDict.Add("D", "Dog");
        myDict.Add("E", "Elephant");
  
        // Displaying the keys and values in StringDictionary
        foreach(DictionaryEntry dic in myDict)
        {
            Console.WriteLine(dic.Key + "  " + dic.Value);
        }
    }
}

Output:

d  Dog
b  Banana
c  Cat
e  Elephant
a  Apple

Example 2:




// C# code to add key and value
// into the StringDictionary
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a StringDictionary named myDict
        StringDictionary myDict = new StringDictionary();
  
        // Adding key and value into the StringDictionary
        myDict.Add("A", "Apple");
        myDict.Add("B", "Banana");
        myDict.Add("C", "Cat");
        myDict.Add("D", "Dog");
  
        // It should raise "ArgumentException"
        // as an entry with the same key
        // already exists in the StringDictionary.
        myDict.Add("C", "Code");
  
        // Displaying the keys and values in StringDictionary
        foreach(DictionaryEntry dic in myDict)
        {
            Console.WriteLine(dic.Key + "  " + dic.Value);
        }
    }
}

Runtime Error:

Unhandled Exception:
System.ArgumentException: Item has already been added. Key in dictionary: ‘c’ Key being added: ‘c’

Note:

Reference:


Article Tags :
C#