amy's lab

August 5, 2008

C# Partial Class – Code Generation

Filed under: C# — Tags: , — amy @ 19

I found C# Partial Class to be very useful in code generation.  I could create a new class with the same class name and add my custom methods to that class, without having to worry about the code generator erasing what I wrote.  Before, code generators usually put some special tags in the code to identify an area where only the code generator can modify.  This is fine, but sometimes, either the code generator or the developer would make mistakes and make the code uncompilable.  With C# Partial Class, I could have something like this:

// MyClassGen.cs - this is generated.
// The file ends with "Gen" to denote a generated class.
public partial class MyClass
{
    // put generated code here
}

// MyClass.cs - this is where I add my custom methods
public partial class MyClass
{

}

This probably would be the only time that I would use C# partial class.

Blog at WordPress.com.