The word dictionary itself means a place where all the information is there, now the similar concept goes in the world of C# coding language, Dictionary are used to store the values but it stores the values on the basis of the Key, every value in dictionary has its own distinctive Key by which it can be accessed, removed and distinguished between other values, collectively they are called as Key-Value pair.
Dictionaries are present in the System.Collection.Generic namespace, the other advantage of dictionaries in C# is that they are dynamic in nature i.e. they can grow according to our need.
Now this is all about the idea and benefits of the dictionary, now let’s see how to create a Dictionary in C#:
Dictionary<string, Int16> Employee = new Dictionary<string, Int16>( );
So in the above syntax we have created a Dictionary with name Employee and provide its type i.e. string and short integer.
Now let’s add elements to our Dictionary:
Employee.Add(“Ambuj” , 24);
Employee.Add(“Mahesh” , 36);
Employee.Add(“Raj” , 41);
So above is the process by which we can add elements to our dictionary, we can also put limit to our dictionary.
Now for getting output of dictionary we will apply foreach loop to our dictionary:
Foreach(KeyValuePair<string, Int16> abc in Employee)
{
Console.WriteLine(“Key : {0} , Value : {1}” abc.Key, abc.Value);
}
So hence by above method we can create a Dictionary in C# and store our values in form of Key-Value pair.