Code Generation in .NET 2.0

personally I would be interested in hearing some opinions on how generics will effect the role of code generation in development. Using generics will be able to define code templates using simple language constructs instead of the brain-dead duplication of code blocks that we have today. Will that make code generation less useful? Or maybe more? On one hand CG will no longer be needed for the "grunt work" of defining typed data structures and the algorithms to handle them. On the other hand, if we use CG to create templates which themselves use generics - now that could be insanely powerful.

[Andy Santo]

I think that template-based code generation and generics are VERY similar. Personally, I can't wait for generics so that I can use them in my CodeSmith templates. Right now I have to have templates that create a separate typed collection class for each entity class that I generate. Generics are going to be awesome for classes that only vary by type, but what happens when I want to go beyond that? CodeSmith templates are based on things like database schema information (soon they will be based on an O/R mapping XML file), strings, boolean flags, and whatever else I can think of. Unlike generics, my templates can also have complex logic in them.

Speaking of generics, the thing I am looking forward to most in .NET 2.0 is partial classes. I believe partial classes are going to be a godsend to code generation. Currently I have to make sure that my entity classes have enough hooks in them so that I can derive from them and add any custom logic that might be needed, with partial classes I will simply be able to generate half of the class, write the other half by hand and not worry about my custom code being overwritten. Is it time for PDC yet?


  • Generics are not templates. They let you specify generic code which applies to any type, however they're NOT the same as the C++ templates. People confuse the two a lot (see a recent thread in the C# newsgroup).

  • It doesn't matter if they are the same as C++ templates or not. I was just saying that template-based code generation and generics are very similar. Generics in .NET 2.0 is simply the ability to expand types at runtime.

    public class Stack<ItemType>


    private ItemType[] items;

    public void Push(ItemType data)


    public ItemType Pop()

    {... }


    When this class is instantiated with new Stack<String> then ItemType is expanded with String throughout the class. That seems like template-based code generation to me.

  • I'm going to agree with Eric on this one. C# generics fall into the set generative programming tools in a similar manner to C++ templates.

Comments have been disabled for this content.