Using Partial Classes to Enable Active Generation

.NET 2.0 offers a new feature that enables active code generation scenarios in both C# and Visual Basic .NET: partial classes. With partial classes, the code for a single class can be split across multiple class declarations, in one or more files. At compile time, the compiler locates all of the pieces of the class and assembles them into a single complied class.

In C#, partial class definitions look like this:

partial class Class1
{
    public void Method1
    {
        // code to implement Method1
    }
}
 
partial class Class1
{
    public void Method2
     // code to implement Method2
    }
}

In Visual Basic, the same example looks like this:

Partial Public Class Class1
    Public Sub Method1
        ' Code to implement Method1
    End Sub
End Class
 
Partial Public Class Class1
    Public Sub Method2
        ' Code to implement Method2
    End Sub
End Class

In either case, you can enable active generation by generating the code for Method1, while keeping the handcrafted code for Method2 in a separate file, untouched by CodeSmith Generator. At compile time, the appropriate compiler will knit the two files together into a single unified class.