Partial Classes (CF & Full FX)

Fri, September 17, 2004, 02:26 AM under Whidbey | VisualStudio
If you create a new Windows Application project in VS2005 you'll notice that viewing the code for the Form1 class shows very little. All the designer generated code is missing. If you then "Show All Files" in the solution explorer, you can see under the Form1.cs file a Form1.Designer.cs file which upon viewing reveals the designer generated code in yet another Form1 class. If you build the project and look into the assembly with ILDASM, you notice exactly one Form1 class and no indication about this split. The clue to the whole mystery is the keyword "partial" before each class declaration (in fact VB allows one class not to be declared as partial so you'll only see "Partial" in the Form1.Designer.vb file).

So this is a tool thing. You can split a class over multiple files in the same project, as long as you declare them as partial. With forms, note that adding event handler methods or any other methods that you write, appear in the main code file.

To complete the story of how the solution explorer links the two in the manner that it does, we simply look at the .csproj/vbproj file in Notepad or your favorite XML editor. Under the ItemGroup tag you find something like this:

    <Compile Include="Form1.cs">

         <SubType>Form</SubType>
    </Compile>
    <Compile Include="Form1.Designer.cs">
        <DependentUpon>Form1.cs</DependentUpon>
    </Compile>

It is the DependentUpon tag that makes a file appear under another in VS. It is being put to very good use with Partial classes.

So here is a money making thought (and you don't even have to turn adsense on). Write a tool/addin that will create these entries. MSFT is not offering anything in the IDE apart for forms, so it is down to tedious manual work at the moment. If I were using it, I'd wish for a menu item when I right click on a code file that offers: "Add Partial". So if I used it on a SomeClass.cs, it would ask me for a name XXX and then create a partial class SomeClass.XXX.cs under SomeClass.cs. The greatest use of this tool would be for upgrading existing projects. When upgrading, VS2005 does not split Form classes, so you have to do all the work manually if you want to fit in with the new environment. Oh, and if you need Beta testers, count me in :-)
Comments are closed.