Solving a Coding Mystery
Everyone likes a good puzzle — unless it's in production, which is what happened here. Can you figure out what the issue is?
Join the DZone community and get the full member experience.
Join For FreeThis was a surprising shock. This code seems so simple, but it does something very different than what I would expect.
var doc = new Dictionary<string,object>
{
["@metadata"] = new Dictionary<string, object>
{
["@id"] = "users/1"
}
["Name"] = "Oren"
};
Console.WriteLine(doc["Name"]);
The question is: Why?
As it turns out, we are missing one character here:
Notice the lack of the comma? Let's see how the compiler is treating this code by breaking it apart into steps, shall we?
First, let's break it into two statements:
var item = new Dictionary<string, object>
{
["@id"] = "users/1"
}
["Name"] = "Oren";
var doc = new Dictionary<string,object>
{
["@metadata"] = item
};
Note that we moved the name line into the first statement since there isn’t a command here. However, what is it actually doing? This looks very strange, but that is just because we have the dictionary initializer here. If we drop it, we get:
That makes a lot more sense. If we break it all down, we have:
var tmp1 = new Dictionary<string, object>();
tmp1["@id"] = "users/1";
tmp1["Name"] = "Oren";
var tmp2 = tmp1["Name"];
var tmp3 = new Dictionary<string, object>();
tmp3["@metadata"] = tmp2;
var doc = tmp3;
Console.WriteLine(doc["Name"]);
That explains it all. It makes perfect sense — and it's a very nasty trap. We ran into it accidentally in production code, and it was near impossible to figure out what was going on or why it happened.
Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments