Dictionary Initialization C#

On this page

    Dictionary Initialization C#

    Introduction

    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.

    ```cs

    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:

    ```cs

    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

    Join our newsletter to get the latest updates
    Sign Up
    Share
    Michael Sacco
    Founder & CEO

    Michael Sacco is the Founder and CEO of OccaSoftware where he specializes in developing game assets for Unity game developers. With a background ranging from startups to American Express, he's been building great products for more than 10 years.

    Tags
    c sharp
    Unity Basics
    programming