C# Dictionary initializer is a functionality that is employed to set initial values for dictionary elements. A dictionary serves as a container for elements, organizing them in key-value pairs.
A dictionary initializer employs curly brackets ({}) to encapsulate the key and corresponding value pairs.
Let's consider an instance where we are setting a value for each individual key.
C# Dictionary Initializer Example 1
using System;
using System.Collections.Generic;
namespace CSharpFeatures
{
class DictionaryInitializer
{
public static void Main(string[] args)
{
Dictionary<int, string> dictionary = new Dictionary<int, string>()
{
[1] = "Irfan",
[2] = "Ravi",
[3] = "Peter"
};
foreach (KeyValuePair<int, string> kv in dictionary)
{
Console.WriteLine("{ Key = " + kv.Key + " Value = " +kv.Value+" }");
}
}
}
}
Output:
{ Key = 1 Value = Irfan }
{ Key = 2 Value = Ravi }
{ Key = 3 Value = Peter }
In this instance, we are saving student information in a dictionary. We are employing a dictionary initializer to store the student details. Take a look at the provided illustration.
C# Dictionary Initializer Example 2
using System;
using System.Collections.Generic;
namespace CSharpFeatures
{
class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
class DictionaryInitializer
{
public static void Main(string[] args)
{
Dictionary<int, Student> dictionary = new Dictionary<int, Student>()
{
{ 1, new Student(){ ID = 101, Name = "Rahul Kumar", Email = "[email protected]"} },
{ 2, new Student(){ ID = 102, Name = "Peter", Email = "[email protected]"} },
{ 3, new Student(){ ID = 103, Name = "Irfan", Email = "[email protected]"} }
};
foreach (KeyValuePair<int, Student> kv in dictionary)
{
Console.WriteLine("Key = "+kv.Key + " Value = {" + kv.Value.ID +", "+ kv.Value.Name +", "+kv.Value.Email+"}");
}
}
}
}
Output:
Key = 1 Value = {101, Rahul Kumar,[email protected]}
Key = 2 Value = {102, Peter,[email protected]}
Key = 3 Value = {103, Irfan,[email protected]}