How is this C# dictionary initialization correct?

The missing comma makes all the difference. It causes the indexer ["OtherAs"] to be applied on this dictionary:

new Dictionary<string, object>
{
    ["Name"] = "Solo",
    ["Points"] = 88
}

So essentially you’re saying:

new Dictionary<string, object>
{
    ["Name"] = "Solo",
    ["Points"] = 88
}["OtherAs"] = new List<Dictionary<string, object>>
{
    new Dictionary<string, object>
    {
        ["Points"] = 1999
    }
};

Note that this is an assignment expression (x = y). Here x is dictionary with “Name” and “Points”, indexed with "OtherAs" and y is the List<Dictionary<string, object>>. An assignment expression evaluates to the value being assigned (y), which is the list of dictionaries.

The result of this whole expression is then assigned to the key “MyA”, which is why “MyA” has the list of dictionaries.

You can confirm that this is what’s happening by changing the type of the dictionary x:

new Dictionary<int, object>
{
    [1] = "Solo",
    [2] = 88
}
// compiler error saying "can't convert string to int"
// so indeed this indexer is applied to the previous dictionary
["OtherAs"] = new List<Dictionary<string, object>>
{
    new Dictionary<string, object>
    {
        ["Points"] = 1999
    }
}

Here is your code, but reformatted and some parentheses added to illustrated how the compiler has parsed it:

["MyA"] 
= 
(
    (
        new Dictionary<string, object>
        {
            ["Name"] = "Solo",
            ["Points"] = 88
        }["OtherAs"] 
    )
    = 
    (
        new List<Dictionary<string, object>>
        {
            new Dictionary<string, object>
            {
                ["Points"] = 1999
            }
        }
    )
)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)