Dictionary Initialization C#

by Michael Sacco Published September 21, 2023
The cover for Dictionary Initialization C#


In this article, I will briefly overview how to create and initialize a dictionary in C#.

It’s easy to do C# inline dictionary initialization. As you know, to initialize a C# dictionary without values, you’ll write something like this.

Dictionary<string, int> playerLevels = new Dictionary<string, int>();

C# Initialize Dictionary with Values

To initialize a c# dictionary with values, you include the dictionary in curly braces as part of the dictionary initialization. Here’s an example.

The most common method of initializing a dictionary in C# is using the Dictionary<TKey, TValue> constructor. Here’s the proper way to initialize a C# dictionary with values.

Dictionary<string, int> playerLevels = new Dictionary<string, int>
  {"ShadowMaster", 78 },
  {"DragonSlayer22", 92},
  {"StealthNinja", 64}

This method is straightforward and suitable for small dictionaries. If you have a large dataset, it can be time-consuming to type out the pair for every value.

C# Dictionary Collection Initializer with Var and Object Initializer

C# also offers a concise syntax that allows you to initialize dictionaries. This approach represents an alternative method. You can initialize the collection either way. To use this approach, you specify the key, then set it equal to the value stored in the dictionary.

var playerLevels = new Dictionary<string, int>
  ["ShadowMaster"] = 78,
  ["DragonSlayer22"] = 92,
  ["StealthNinja"] = 64

This method simplifies the code and is suitable for smaller dictionaries. But it still requires manual entry. Manual entry is not ideal. But you should expect it when doing initialization in this manner.

In Unity, using var to initialize a dictionary is not always valid. This method only works when initializing the dictionary as part of the script code. You can’t use var to initialize the dictionary outside of a method.

C# Initialize dictionary from List.

You can use LINQ to initialize a dictionary. For example, let’s assume you already have the data in another collection, such as a list. In this case, use LINQ to transform the List to a Dictionary. This approach is handy when dealing with larger datasets:

var players = new List<Player>
  new Player("ShadowMaster", 78),
  new Player("DragonSlayer22", 92),
  new Player("StealthNinja", 64)

var playerLevels = players.ToDictionary(e => e.GamerTag, e => e.Level);

The proper way to initialize a C# dictionary, then set values later

// Initialize an empty dictionary
var playerLevels = new Dictionary<string, int>();

// Set values for the dictionary
playerLevels["ShadowMaster"] = 78;
playerLevels["DragonSlayer22"] = 92;
playerLevels["StealthNinja"] = 64;

In this example, we first create an empty Dictionary<string, int>. Later in the code, we assign values to this dictionary using the keys. We generate the dictionary key-value pair when that assignment. This approach has some benefits. For example, you can populate the dictionary as needed in your game.

Recommended Reading

Free download: Indie Game Marketing Checklist

Download now


c sharp

Don't forget to share this post!

Popular assets for Unity

See all assets ->
    Cutting-edge volumetric fog and volumetric lighting with support for transparent materials.
    Volumetric clouds, day night cycles, dynamic skies, global lighting, weather effects, and planets and moons.
    Super Simple Skybox
    A lightweight procedural skybox ideal for semi-stylized projects.
    Gaussian Blur
    Per-pixel gaussian blur on your entire screen, part of the UI, or in-scene objects.
    Image-based Outlines for 2D and 3D games with variable line weight, color, and displacement options.
    Auto Exposure
    Avoid blown-out highlights and too-dark shadows with automatic exposure metering.

Free Indie Game Marketing Checklist

Learn how to make your game successful with this handy checklist.

Download for free