# Thursday, 22 June 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,

    CodeBinaryOperatorType.IdentityInequality,

    new CodePrimitiveExpression(null))

    );

CodeMethodInvokeExpression convertExpr = new CodeMethodInvokeExpression(

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

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

    );

ifArrayNotNull.TrueStatements.Add(convertExpr);

to make this

if(myObject.Property != null)

{

    Convert.ToBase64String(myObject.Property);

}

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, 26 June 2006 01:12:39 (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, 02 August 2006 14:48:52 (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
Matt Schwartz
Comments are closed.