Let us say, we have a Dictionary that contains,
As Key and Value pair.
Now, let us say, we want to insert a new entry,
Where Rose is the Key and Is a Flower is its corresponding Value.
Let us see in the below example.
using System.Collections.Generic; public class MyApplication { public static void Main(string[] args) { Dictionary<object, string> x = new Dictionary<object, string>() { { 5, "Is a Number" }, { "John", "Is a Name" }, { "C#", "Is a Language"} }; x["Rose"] = "Is a Flower"; foreach (KeyValuePair<object, string> i in x) { System.Console.WriteLine("The key is : "+i.Key+" and the value is : "+i.Value); } } }
So, in the above code we have created a Dictionary using braces {} and Key and Value pairs.
Dictionary<object, string> x = new Dictionary<object, string>() { { 5, "Is a Number" }, { "John", "Is a Name" }, { "C#", "Is a Language"} };
And initialised to the variable x.
Now, we are supposed to add a new entry to the Dictionary. Where the Key would be Rose and the Value Is a Flower.
So, we have used the below way to add it.
x["Rose"] = "Is a Flower";
And the entry is added to the Dictionary.
And we get the below output,
Let us say, we have a Dictionary that contains,
As Key and Value pair.
Now, let us say, we want to insert a new entry,
Where John is the Key and Is an English Name is its corresponding Value.
Let us see in the below example.
using System.Collections.Generic; public class MyApplication { public static void Main(string[] args) { Dictionary<object, string> x = new Dictionary<object, string>() { { 5, "Is a Number" }, { "John", "Is a Name" }, { "C#", "Is a Language"} }; x["John"] = "Is an English Name"; foreach (KeyValuePair<object, string> i in x) { System.Console.WriteLine("The key is : "+i.Key+" and the value is : "+i.Value); } } }
So, for the Key, John the initial value was Is a Name.
Dictionary<object, string> x = new Dictionary<object, string>() { { 5, "Is a Number" }, { "John", "Is a Name" }, { "C#", "Is a Language"} };
And we wanted to add a new entry with the Key as John and the Value as Is an English Name.
x["John"] = "Is an English Name";
But if we see the output.
We can see the Key, John is updated with the Value, Is an English Name.
That's because duplicate Keys are not allowed in Dictionary. The corresponding value for that Key will get updated with the new Value.