Category Archives: Code Generation

Draft – .NET Code Generation

What the heck is code generation?

Code generation is an old idea, that people hobbled together solutions to make it happen. Lets start by showing a few examples of it:

  • Lets say you are writing a class in .NET but many of its properties are based on fields in a database table. For example if the database has 25 fields the class will have 25 properties that map to the database fields. Sure you could type out the property names and types once and have the 25 properties in your class and be done. That is until they add or remove table fields or rename them, and you must go back to your editor and add/delete/rename ad nauseum.  If you have 30 tables that you are wrapping into corresponding objects DBMS changes mean a lot of tedious work to keep them in sync. A code generator could just loop through field names and types dynamically and generate corresponding properties. Update the database tables, then regenerate the code and dozens or hundreds of classes are updated.
  • Now for a simpler example. Let us say you know that the query SELECT * from Location is slower than the query SELECT id,city,state,zip from location.  This could be streamlined by creating a code generating function inline i.e. SELECT <%FieldNames(“Location”)%> from location which expands before compilation to the latter SELECT with an explicit field list.

CodeSmith and FREE T4 – The Coke and Pepsi of Code Generation

In all marketing wars there ends up being 2 leader once the market becomes mature. A strong #1 can “suck the oxygen out of the room” and delay 1 #2 rising, at the risk of the category dying entirely.

Code Generation for .NET there are 2 players

CodeSmith is fairly neutral and can generate any code for any language or platform. T4 is coupled to .NET and visual Studio. Most ORMs for .NET use one of  these two to generate their classes.

Another Approach or 2 or 3

These are just one approach to Code Generation, a simple and easy one.

  • the Roslyn project is yet another focused on the more compiler writer type of person. Read more about the Roslyn project @
  • CodeDom allows one to write .NET code dynamically, and combined with Reflection to read the code entities at runtime it is an approach that many used who do not know these tools or just prefer this approach and the runtime checking it provides.
  • All this often dovetails with use of attributes.

What about code generation on other platforms?

  • Linux
  • Mac
  • iOS
  • Android