.Net framework Dictionary<TKey, TValue>.Add() method allow us to add the specified key and value to the dictionary. dictionary Add() method exists in System.Collections.Generic namespace. Add() method need to pass two parameters named ‘key’ and ‘value’.
the ‘key’ parameter value type is ‘TKey’ which represents the key of the element to add. ‘value’ parameter value type is ‘TValue’ which represents the value of the element to add into dictionary. this value can be null for reference types. ‘key’ cannot be null. this method implements as IDictionary<TKey, TValue>.Add(TKey, TValue).
dictionary Add() method throw ArgumentNullException exception if the ‘key’ parameter value is null. this method throw ArgumentException exception, if an element with the same key already exists in Dictionary<TKey, TValue>.
the following c# example code demonstrate us how can we add a key and value pair to dictionary programmatically in an application.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class Program { static void Main(string[] args) { Dictionary<string, string> colors = new Dictionary<string, string>(); colors.Add("AliceBlue", "#F0F8FF"); colors.Add("AntiqueWhite", "#FAEBD7"); colors.Add("BlueViolet", "#8A2BE2"); colors.Add("CadetBlue", "#5F9EA0"); Console.WriteLine("Dictionary Keys....."); foreach (string color in colors.Keys) { Console.WriteLine(color); } colors.Add("CornFlowerBlue", "#6495ED"); Console.WriteLine("\nAfter Adding 'CornFlowerBlue'. Dictionary Keys....."); foreach (string color in colors.Keys) { Console.WriteLine(color); } Console.ReadLine(); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Dictionary Keys..... AliceBlue AntiqueWhite BlueViolet CadetBlue After Adding 'CornFlowerBlue'. Dictionary Keys..... AliceBlue AntiqueWhite BlueViolet CadetBlue CornFlowerBlue |