How To Initialize A Dictionary In C#

How To Initialize A Dictionary Banner Image

Introduction

C# offers several ways to initialize a dictionary at compile time. Because oftentimes there's a dictionary that you just want to hold a few values for some look-ups for other structures in the code. It may not change so it can be set and left alone. So C# offers the collection initializers to quickly do this where the dictionary itself is declared.

Motivation

The most basic way to initialize a dictionary is to declare the dictionary and add a few additional statements for each of the key-value pairs that you want to add. See the example below.

Dictionary<string, string> salaryDictionary = new Dictionary<string, string>();
InitializeDictionary();
PrintDictionary();

void InitializeDictionary()
{
    salaryDictionary.Add("Bob", "50000");//Add Key Value Pair To Dictionary
    salaryDictionary.Add("Jil", "60000");//Add Key Value Pair To Dictionary
    salaryDictionary.Add("John", "70000");//Add Key Value Pair To Dictionary
    salaryDictionary.Add("Jen", "80000");//Add Key Value Pair To Dictionary
}

void PrintDictionary()
{
    foreach (KeyValuePair<string,string> salaryEntry in salaryDictionary)
    {
        Console.WriteLine($"name:{salaryEntry.Key}, yearly salary:{salaryEntry.Value}");//Print Values
    }
}
Code Output
name:Bob, yearly salary:50000
name:Jil, yearly salary:60000
name:John, yearly salary:70000
name:Jen, yearly salary:80000

We can simply write code like this. But this has several drawbacks. There is a lot more code that we need to write to make this happen. Also, what if we make a mistake in the code or duplicate the keys then an error can occur. Then we wouldn't find out until after our program started. There is a better way.

Collection Initializers

There are two ways to use the Collection Initializer. The first way is called the add Collection Initializer and the second is Index Initializer.

Add Collection Initializers

This lets you Initialize the dictionary on the same line as the declaration statement. The interesting thing is when this syntax is compiled. It is translated into Add statements, but in the IDE it shows just one line. Below is how it looks in the previous example.

Dictionary<string, string> salaryDictionary = new Dictionary<string, string>() { { "Bob", "50000" }, { "Jil", "60000" }, { "John", "70000" }, { "Jen", "80000" } };//Initialize the dictionary with a Colleciton Initializer
Translated To By The Compiler
    Dictionary<string, string> salaryDictionary = new Dictionary<string, string>();
    salaryDictionary.Add("Bob", "50000");
    salaryDictionary.Add("Jil", "60000");
    salaryDictionary.Add("John", "70000");
    salaryDictionary.Add("Jen", "80000");

This does a few things. Reduces the code written. It is less prone to error. This works best if you only don't have too many entries in the dictionary to put.

Index Initializer

Another way we can do this is to the Index Initializer which is another type of Collection Initializer. It was similar to the previous example in that it goes on the same line. The syntax allows an indexer to be assigned a value. See the example below.

Dictionary<string, string> salaryDictionary = new Dictionary<string, string>() { ["Bob"] = "50000", ["Jil"] = "60000", ["John"] = "70000", ["Jen"] = "80000" };//Initialize the dictionary with a Index Initializer
Translated To By The Compiler
Dictionary<string, string> salaryDictionary = new Dictionary<string, string>();
salaryDictionary["Bob"] =  "50000";
salaryDictionary["Jil"] = "60000";
salaryDictionary["John"] = "70000";
salaryDictionary["Jen"] = "80000";

This syntax sets only indexes that we specify.

C# Programming for Unity Game Development Specialization

COURSERA

C# Programming for Unity Game Development Specialization

4.7 (2,230 reviews)

Beginner level

No previous experience is necessary

3-months at 10 hours a week (At your pace)

$59 / month or audit, and financial aid available

If you want to learn more about C# then check out this course on Coursera. It's a 3 month course to take you through the basics of C#.

You can get started with programming using C# and apply it to Unity games in this beginner-level program. Facilitated by the University of Colorado, the program offers a chance to grasp the basics of C# and utilize the knowledge to develop Unity games.

[Full Disclosure: As an affiliate, I receive compensation if you purchase through this link]

Start Your 7-day Free Trial

Conclusion

Collection Initializers give more compact and readable code. It simplifies the code so we would be more productive because of the compile checks.

Get Latest Updates