Alexander Beletsky's development blog

My profession is engineering

A little bit on Javascript magic inside C# code

C# and Javascript are both my favorite languages. I believe that those two are best languages in a world (perhaps I haven’t started to learn Ruby). With a quite long practice in Javascript, you start to feel real power of dynamic language. Even more, you are so much get used for particular code constructions that you try to do the same things in C#.

This is something you might do in javascript a lot. Consider that code,

code

Method createConfig takes options object, dynamically construct config object and returns it back to client. Maybe it is the best example, but shows - I dynamically able to construct an object, just putting new properties into it.

Now, let’s try to do that same with C#. Believe me or not, but I can do exactly (OK, mostly exactly) code with C#.

code

We can play “Find a difference” game here. Anyway, what I can say: “anonymous types + dynamic + ExtendoObject”, is a magic spell that turn you C# code into Javascript.

  • With Anonymous Types you easy get a notion of JavaScript dynamic object, just use new { MyProp = 1 } JavaScript analog { MyProp: 1 }.
  • Dynamic would tell to compiler - “Do not check my type now, let Runtime do that”. So, with dynamic objects you can do obj.MyProp, compiler would allow this code, existence of property would be checked on runtime, if absent - exception will be thrown.
  • ExpandoObject is a super-power of .NET, allows you to construct object at runtime. You can see, that I just assign new property, that property would be dynamically added to config object.

Life would not be so interesting if every thing is so easy. My first implementation failed to work, in line if (option.Ip || option.Proto) then I called createConfig with object that actually contains no such properties. As I said above, dynamic simply throws an exception if property is missing. I could wrap code in some try / catch cases, but it would be to ugly and magic would gone. We have to extend our magic formula with one component - Reflection. So, let’s pronounce spell again, “anonymous types + dynamic + ExtendoObject + Reflection” and check out final secret piece of code.

DynamicProxy is simple wrapper around the dynamic, it overloads [] operator and check availability of property using Reflection.

code

That’s it. I’ve made C# code look like and behave like JavaScript, utilizing power of .NET platform. As always, you can find a source code on github - csharp-js.

Disclaimer

You should not probably doing such tricks a lot. C# is still static language (even with dynamic features in it). It is better to rely on types, wherever it is possible to.. The code above is created to solve my particular problem and I had a lot of fun detecting this C# and JavaScript analogy. But now I still thinking to re-write that to statically typed less-beauty, less-magic solution :).