« 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:
-
Partial method declarations must begin with the contextual keyword partial and the method must return void.
-
Partial methods can have ref but not out parameters.
-
Partial methods are implicitly private, and therefore they cannot be virtual.
-
Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.
-
Partial methods can have static and unsafe modifiers.
-
Partial methods can be generic. Constraints are placed on the defining partial method declaration, and may optionally be repeated on the implementing one. Parameter and type parameter names do not have to be the same in the implementing declaration as in the defining one.
-
You can not make a delegate to a partial method.
Posted by Hartmut Wilms at 11.04.07 17:32