Another use of partial types

Tue, August 2, 2005, 04:03 PM under Whidbey | VisualStudio
We've looked at partial types before but what use are they?

Their primary use is for code generation tools. The main/best example is the windows forms designer which uses them for splitting the designer code from the code we (the developers) write. I think that code generation will play an even larger part in every day development as years go by but that is another story...

Another use could be to split a class in privates and publics. So one file has all the (private) fields and private methods while the other has all the members that are externally callable.

You can take the previous idea too far and have a file per member category i.e. one for fields, one for methods, one for properties and one for events (or even another for internal types such as structs/classes/delegates).

If a class implements an interface (or many), why not split the interface implementation into its own file...

Some might even split a class into files according to the areas that different developers are working on (thus assisting with source control check ins/outs).

Finally, if you find yourself declaring your own code regions in VS.NET 2003, consider whether you can extract them into their own file using partial classes.

I am not advocating any of the above but I am not being a purist against it either. For the record, I do believe that classes should be controlled from growing too large; objects should be designed to do one thing only and do it well.

Recently I discovered another reason. A few years back, when I migrated a whole bunch of dotnet code to the compact framework, I came across types that while designed to do one thing only, they had a fatter interface than what appropriate for an embedded platform (and some of their members were simply not applicable to windows ce). There were a number of approaches I took depending on the situation:
1. "Carry" the extra class members but not call them
2. Conditionally compile parts of the class for the NETCF (or vice versa)
3. From a single class, extract a base abstract class and two specialisations (each in their own file). In the Smart Device Project I only use two files out of the three (the base class and only the one subclass that is applicable).

It is obvious where this is going, isn't it? :-)

A 4th option with Visual Studio 2005 is to use partial classes and thus exclude the files you don't want from one of the projects. One more support option for sharing projects between the two platforms.
Comments are closed.