This page looks best with JavaScript enabled

Inline Initializing C# Dictionaries - Quick Tip

 ·   ·  ☕ 1 min read

    C# allows you to seed data into your dictionary when it’s constructed by using an initializer function that accepts a series of key, value pairs after its constructor that causes those elements to be automatically inserted into your Dictionary’s for you. This is a really handy way to initialize your dictionaries if you already know what you expect to be a part of them or want to use a Dictionary as a lookup table for example.

    An example of what this might look like:

    1
    2
    
    // Note: replace angled brackets with correct character!
    var myList = new Dictionarystring,string() { {"key", "value"}, {"key2", "value2"} };
    

    Doing this traditionally would look like this:

    1
    2
    3
    4
    
    // Note: replace angled brackets with correct character!
    var myList = new Dictionarystring,string();
    myList.Add("key", "value");
    myList.Add("key2", "value2");
    

    This trick also works for Lists! Here’s how: https://youtu.be/F11BhVjmyd0

    Join the World of Zero Discord server: https://discord.gg/hU5Kq2u


    Sam Wronski
    WRITTEN BY
    Sam Wronski
    Maker of things, currently helping build cloud things @ Google. World of Zero is a personal project disconnected from my professional work. Lets make something awesome together!