OdeToCode IC Logo

The Promise of Partial Classes and ASP.NET

Friday, April 21, 2006

Web site projects in Visual Studio 2005 give us exactly one code-beside file per web form. We specify the name of the file with the CodeFile attribute in the form’s @ Page directive. There can be no other file – a web form and its code-beside file maintain a monogamous relationship.

But wait! Partial classes in C# and Visual Basic say I can:

“…split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled.”

True, true, but there is no capability to specify multiple files with the CodeFile attribute, and the CodeFile attribute is the only piece of information the ASP.NET runtime has available to know what else it needs to compile with the web form (each web form can compile into a distinct assembly). I can’t drop a partial class definition for the web form into App_Code, either, because App_Code compiles into a separate assembly, and partial class definitions cannot span multiple assemblies.

Let’s approach the problem from a different angle: why would we want a web form’s code-behind to span multiple files? Is the class hard to manage because it has too much code inside? That scenario sounds like an architectural problem that can’t be solved with the partial keyword. Do we want to cleanly separate event handlers from virtual overrides? Perhaps a #region would do a better job.

Web Application Projects are a different matter. WAP allows multiple partial class definitions. In fact, WAP itself will create two source code files for each web form. One file is for human generated code, and the other file is for designer generated code. This scenario is an ideal candidate for partial classes. With WAP, Visual Studio compiles all of the .cs/.vb code-behind files at once, and into a single assembly. WAP allows the compiler to merge partial class definitions.