On-the-fly Code Generation with .NET Expression Trees

Recently I came to the task to fill a bunch of C# object properties from a Dictionary. There were 10+ fields and I decided to use reflection to avoid writing and supporting dummy code on every object change.

So I come up with code like:


typeof(DataObject).GetProperties().Where(...).Select(x=>x.SetValue(instance, GetValue(x), null));

Of course this code was not fast. I used Reflection and LINQ. The task was to make it work faster. First I decided to drop all reflection code and write all bindings explicitly for every field. Than I come up with another trick!

Why not to make .NET LINQ Expressions runtime generate this code for me at runtime. It was easy to implement and performance was close to hand-written. First, I moved all initialization of Expressions outside of binding code. So the binding turned out to be an array iteration and delegates call.

Let's see how to make Expressions generate a code for property binding.

Using this code I generate a code that sets property value without reflection!

The fun is that one may make a next step to include all parsing and validation logic into this code and thus have a generated code for it. This is really handy that C# allows to write the following code:

This is a simplest way to get Expression tree for simple lambdas.

comments powered by Disqus