Programming Puzzle: Simple C# Code Generation

Difficulty: Moderate

2 min readJun 11, 2020

--

As can be seen from my previous posts I love small making small programming exercises. Exercises can remove irrelevant distractions while we’re learning something specific. They help us stay sharp! I recently came up with this fun little puzzle in C#, can you solve it?

Generating code can be an invaluable skill in software development. Common situations where we use code generation include: for consuming an API, classes representing a database schema, or compiling a domain-specific language.

Puzzle

You need to create a function in C# that can take in a Dictionary<string, object> and give back a string containing runnable code to get that Dictionary. You are not allowed to inspect the runtime type, use casts, or type conversion.

Your main function should be:

static void Main(string[] args)
{
var dic = new Dictionary<string, object>();
dic["one"] = "hello";
dic["two"] = 5;
dic["three"] = true;
dic["four"] = "False";
string result = your_function(dic);
Console.WriteLine(result);
Console.Read();
}

Running it should print:

var dic = new Dictionary<string, object>();
dic["one"] = "hello";
dic["two"] = 5;
dic["three"] = true;
dic["four"] = "False";

If you like working with code you might like my refactoring book:

--

--

Christian Clausen
Christian Clausen

Written by Christian Clausen

I live by my mentor’s words: “The key to being consistently brilliant is: hard work, every day.”

No responses yet