I stumbled upon the following and I'm wondering why it didn't raise a syntax error.
var dict = new Dictionary<string, object>
{
["Id"] = Guid.NewGuid(),
["Tribes"] = new List<int> { 4, 5 },
["MyA"] = new Dictionary<string, object>
{
["Name"] = "Solo",
["Points"] = 88
}
["OtherAs"] = new List<Dictionary<string, object>>
{
new Dictionary<string, object>
{
["Points"] = 1999
}
}
};
Notice that the "," is missing between the "MyA", and "OtherAs".
This is where the confusion happens:
- The code compiles.
- The final dictionary "dict" contains only three elements: "Id", "Tribes", and "MyA".
- The value for all except "MyA" are correct,
- "MyA" takes the declared value for "OtherAs", while its original value is ignored.
Why isn't this illegal? Is this by design?
OtherAsgets added as a key into what would be theMyAdictionary. (Name=Solo, Points=88 plus OtherAs=List<Dictionary <string, object>>) except it then never assigns it. Instead it places the list of dicts, now only containing the single Points=1999 entry into theMyAslot overriding what one would think belongs there.<string, string> and modify Points to"88"` you then get a compiler error "Cannot implicitly convert type 'System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, object>>' to 'string'" which actually helped me figure out the answer!var test = new Dictionary<string, object> { ["Name"] = "Solo", ["Points"] = 88 }["OtherAs"] = new List<Dictionary<string, object>> { new Dictionary<string, object> { ["Points"] = 1999 } };will explain it further.