# Thursday, June 22, 2006

I’m a huge fan or runtime code generation.  I think it solves a lot of common problems in modern applications.  However, the .NET implementation of runtime code gen, a.k.a. the CodeDOM, is viciously difficult to learn and use.  I think that’s holding many people back from implementing good solutions using runtime codegen. 

For example, it takes all this

CodeConditionStatement ifArrayNotNull = new CodeConditionStatement(

    new CodeBinaryOperatorExpression(propertyRef,


    new CodePrimitiveExpression(null))


CodeMethodInvokeExpression convertExpr = new CodeMethodInvokeExpression(

    new CodeTypeReferenceExpression(typeof(Convert)),"ToBase64String",

    new CodeExpression[] { new CodeCastExpression(typeof(byte[]),propertyRef)}



to make this

if(myObject.Property != null)




Not only is it a lot more code using the CodeDOM, but it’s certainly not the kind of code that you can just pick up and understand. 

There must be an easier way.  Refly helps a bunch, but last time I tried it I found it to be incomplete.  It’s certainly a step in the right direction.  It’s certainly a model that’s much easier to understand.  I wonder if, in the end, it’s too limiting?  There may be a good reason for the complexity of the CodeDOM.  Or there may not be.

Monday, June 26, 2006 1:12:39 AM (Pacific Daylight Time, UTC-07:00)
I *TOTALLY* agree. I looked at doing code gen in code once, saw the amount of code I would have to write, and said f**k it. Literally.

I think other, more dynamically typed, languages make this a lot easier.
Wednesday, August 02, 2006 2:48:52 PM (Pacific Daylight Time, UTC-07:00)
Yep, code gen is probably the most difficult task of .Net programming that I've came across as well. I used it once to have VS.NET auto-generate a singleton class that gave strongly named properties to key-value members of a .resx file. I do although think it's a good idea for every developer to use CodeDom once though as it gives you some pretty good insight on the interworkings of C# and it's syntax.

Matt Schwartz
Comments are closed.