Using Dictionary Initializers in C#: A Concise Way to Create and Populate Dictionaries

Learn how to use dictionary initializers in C# to create and populate `Dictionary` objects efficiently. This tutorial explains the syntax of dictionary initializers, demonstrates their use with various data types (integers, strings, custom objects), and shows how to create dictionaries with pre-defined key-value pairs for improved code readability.



Using Dictionary Initializers in C#

What is a Dictionary Initializer?

In C#, a dictionary initializer provides a concise way to create and populate a `Dictionary` object. Dictionaries store data as key-value pairs, making them useful for various data management tasks. Dictionary initializers use a compact syntax, making it easier and more readable to create dictionaries with pre-defined elements.

Dictionary Initializer Syntax

Dictionary initializers use curly braces {} to enclose key-value pairs. Each key-value pair is separated by a comma, and the key and value are separated by a colon.

Example: Simple Key-Value Pairs

Dictionary<int, string> myDictionary = new Dictionary<int, string>() {
    { 1, "One" },
    { 2, "Two" },
    { 3, "Three" }
};

Example 1: Initializing a Dictionary with String Values

This example demonstrates initializing a dictionary with integer keys and string values using a dictionary initializer. The `foreach` loop iterates through the dictionary and prints each key-value pair.

C# Code

using System;
using System.Collections.Generic;

public class DictionaryInitializerExample {
    public static void Main(string[] args) {
        Dictionary<int, string> myDict = new Dictionary<int, string>() {
            { 1, "Irfan" },
            { 2, "Ravi" },
            { 3, "Peter" }
        };
        // ... rest of the code ...
    }
}

Example 2: Initializing a Dictionary with Objects

This example shows how to initialize a dictionary with integer keys and custom objects (of type `Student`) as values.

C# Code

using System;
using System.Collections.Generic;

public class Student {
    public int ID { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

public class DictionaryInitializerExample {
    public static void Main(string[] args) {
        Dictionary<int, Student> myDict = new Dictionary<int, Student>() {
            { 1, new Student { ID = 101, Name = "Rahul", Email = "rahul@example.com" } },
            // ...more student objects...
        };
        // ... rest of the code ...
    }
}

Conclusion

Dictionary initializers are a concise and efficient way to populate dictionaries in C#. They improve code readability and reduce boilerplate compared to manually adding each key-value pair.