Tuesday, January 08, 2008

Partial Methods, Join the Fun

We recently updated to Visual Studio 2008 and have been starting to dip our toes into the new functionality that the platform offers. Most recently, we've been investigating the use of partial methods. We make use of code generation, but we have always run into issues with overriding generated methods. Now, using partial methods, we can extend a generated method to accomodate additional logic. We end up with something like:


GenClass1.cs
partial void DoSomethingExtension();

public void DoSomething()
{
//Do things in here that are generated
DoSomethingExtension();
}

CustomClass1.cs (partial class of GenClass1)
partial void DoSomethingExtension()
{
//Do custom adjustments here
}



Of course I don't think this is a great option for standard coding except for specific instances, but in the code generation world, this fits in nicely. One other nice feature is this: if you don't implement a CustomClass1, DoSomethingExtension is taken out at compile time.

No comments: