« LINQ for NHibernate | Main | WCF Dynamic Proxy »

11.04.07

Partial Methods: the Missing Pieces of Code Generation

Partial Classes, a C# 2.0 language feature, are mainly used within code generation. What’s missing today is a means of customizing generated methods. Let’s say your code generator generates a method, which does “something”:

private void MyGeneratedMethod() {
    ...
    // Do Something
    ...
}

If someone wants to add any kind of pre- or post-processing surrounding this “something”, he’s out of luck. Traditionally this problem is solved by introducing protected areas into the generated code. These areas contain code, manually added by the developer, which is “protected” from being eliminated by subsequent code generations. The code generator has to identify these areas and act accordingly. The “protected areas” approach isn’t fool-proof, because protected areas can easily be removed without notification. Partial Methods to the rescue:

 

// In MyGeneratedClass.generated.cs 
public partial class MyGeneratedClass { 
 
    private void MyGeneratedMethod() {
        MyGeneratedMethodPreprocessing();
        // Do Something
        MyGeneratedMethodPostprocessing();
    } 
 
    partial void MyGeneratedMethodPreprocessing(); 
    partial void MyGeneratedMethodPostprocessing(); 
 
} 
 
// In MyGeneratedClass.cs 
public partial class MyGeneratedClass { 
    partial void MyGeneratedMethodPreprocessing() {
        // Do some preprocessing
    }
    partial void MyGeneratedMethodPostprocessing() {
        // Do some postprocessing
    }
} 

Partial Methods separate method definition and implementation. A defined method does not have to be implemented, i.e. if a partial method definition isn’t implemented, all calling code is removed by the compiler.

Galin Iliev summarizes the restrictions on partial methods in his blog entry:

Posted by Hartmut Wilms at 11.04.07 17:32