Code Generation using LINQ Expression Trees and .NET 3.0

via this thread on theServerSide I found this very interesting blog which talks a lot about C# 3.0 news features, including deep hacks and tricks using LINQ and Expression trees in .NET 3.0.

For example, he shows how to do code generation using the Expression tree API instead of using IL, CodeDOM or anything else. Very interesting!

Published Sunday, March 04, 2007 8:41 AM by RoyOsherove
Filed under: , ,

Comments

# Cheat Codes » Code Generation using LINQ Expression Trees and .NET 3.0

Sunday, March 04, 2007 3:08 PM by FransBouma

# re: Code Generation using LINQ Expression Trees and .NET 3.0

I still find the code too horrible to look at, all that reflection and late binding goo... I feel this misses the point. Linq is about writing functionality which is checked at compile time. Doing things behind the scenes to get stuff generated at RUNTIME, has to be deterministic/predictable: i.e. query Q always results in SQL S. This code seems to me more like 'it can be done'-code but hardly useful.

Thursday, March 15, 2007 2:30 PM by Jafar

# re: Code Generation using LINQ Expression Trees and .NET 3.0

Hi Frans,

I'm a long-time reader of your blog.  I relied on some of your excellent data-binding articles when I was trying to do MDD a few years ago.

I strongly disagree with your assertion that metaprogramming is not useful simply because it is not type-checked at compile time.  The fact is that building DSLs is very productive and this is a worthwhile tradeoff.  The alternative would have had me produce reams and reams of serialization code that, while slightly different every time, was essentially the same.  As I mention in the blog, Microsoft uses the same solution for XML serialization.

Runtime code generation has many well documented uses.  The fact that I used LINQ queries to create the expression tree is just a bonus.  If Microsoft had intended you not to use the Expression namespace to generate code, they would have made the constructors internal instead of making helpful factory functions for you to use.

It's important not to get hooked up on looking at LINQ as just a way of strongly-typing database interaction.  With your background in OR mappers it's easy to how you might look at it that way.  In reality LINQ is a way of making it easier for .NET languages to do some very old, well-established functional programming tricks.  Strongly-typed database access is just one of the benefits of strengthening the language with these new concepts.  I've since posted a lot more on my blog about this.  Have another look and let me know how you feel in the comments.