Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Solving a Coding Mystery

DZone's Guide to

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?

Free Resource

RavenDB vs MongoDB: Which is Better? This White Paper compares the two leading NoSQL Document Databases on 9 features to find out which is the best solution for your next project.  

This 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:

image

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:

image

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.

Get comfortable using NoSQL in a free, self-directed learning course provided by RavenDB. Learn to create fully-functional real-world programs on NoSQL Databases. Register today.

Topics:
performance ,code analysis ,bugs

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}