C#Scripting [SOLVED]: Dictionary initializer has different behavior and raises run-time exception when used in combination of array initializer

C#Scripting [SOLVED]: Dictionary initializer has different behavior and raises run-time exception when used in combination of array initializer

Home Forums Scripting C# Tutorials C#Scripting [SOLVED]: Dictionary initializer has different behavior and raises run-time exception when used in combination of array initializer

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #132784

    Cloudy Point
    Keymaster

    QuestionQuestion

    I have the following C# code which initializes a new dictionary with int keys and List<string> values:

    var dictionary =
        new Dictionary<int, List<string>>
        {
            [1] = new List<string> { "str1", "str2", "str3" },
            [2] = new List<string> { "str4", "str5", "str6" }
        };
    

    If I decompile an executable made from this snippet back to C# the corresponding part looks like this:

    Dictionary<int, List<string>> expr_06 = new Dictionary<int, List<string>>();
    expr_06[1] = new List<string>
    {
        "str1",
        "str2",
        "str3"
    };
    expr_06[2] = new List<string>
    {
        "str4",
        "str5",
        "str6"
    };
    

    Everything seems normal and is working properly here.

    But when I have the following code:

    var dictionary2 =
        new Dictionary<int, List<string>>
        {
            [1] = { "str1", "str2", "str3" },
            [2] = { "str4", "str5", "str6" }
        };
    

    which again seems like normal code and compiles successfully, but during runtime I get the following exception:

    System.Collections.Generic.KeyNotFoundException: ‘The given key was not present in the dictionary.’

    When I look into the decompiled code of the second example I can see that it is different from the first one:

    Dictionary<int, List<string>> expr_6E = new Dictionary<int, List<string>>();
    expr_6E[1].Add("str1");
    expr_6E[1].Add("str2");
    expr_6E[1].Add("str3");
    expr_6E[2].Add("str4");
    expr_6E[2].Add("str5");
    expr_6E[2].Add("str6");
    

    And of course this explains the exception.

    So now my questions are:

    1. Is this expected behavior and is it documented somewhere?

    2. Why is the syntax above allowed but the following syntax is not?

      List<string> list = { "test" };
      
    3. Why is the following syntax not allowed then?

      var dict = new Dictionary<int, string[]>
      {
          [1] = { "test1", "test2", "test3" },
          [2] = { "test4", "test5", "test6" }
      };
      

    Similar but different questions:

Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.