In the .NET Framework 2.0, it is possible to split the definition of a few syntax elements (classes, structs, and interfaces) over two or more source files. Each source file will contain a fragment of the class definition, and all parts are combined together and rebuilt at compile time. Here's an example:t
// Save this fragment to foo1.cs public partial class Foo { public void DoThis() { } } // Save this fragment to foo2.cs public partial class Foo { public void DoThat() { } }
The source code of the class Foo belongs to two different files-foo1.cs and foo2.cs. The compiler figures out that Foo is a partial class and looks for sections of its implementation in all the files it is called to process.
csc /t:library /out:foo foo1.cs foo2.cs
The preceding command line does the trick and generates a foo.dll assembly that contains a Foo class with two methods: DoThis and DoThat.
All portions of a type definition meant to be parts of the same type must be declared with the partial keyword and belong to the same assembly and module. Nested partial types are allowed in partial type-definitions, as follows:
partial class Foo { partial class Bar {} } partial class Foo { partial class Bar {} }
When merging two or more partial type-definitions, attributes, interfaces, methods are fused together.
What kind of advantages can a partial type-definition bring to the table? There are several situations when such a solution is desirable. For example, when working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously. In addition, code can be added to the class without having to recreate the source file. Visual Studio .NET 2005 largely uses this approach when creating Windows Forms, web service wrapper code, and so on. Likewise, the programmer can create code that uses these classes, without having to edit the file created by Visual Studio.
Partial classes are widely employed in the generation of the dynamic classes that make an ASP.NET application run. Just the use of partial classes made it possible, in ASP.NET 2.0, to remove all that ugly auto-generated designer-specific code that adorned any code-behind file created with Visual Studio .NET 2003.
Partial classes also give you a more elegant approach to extend auto-generated files such as the reference file of a .NET web service. If you need to add some code, you no longer need to edit the file but can simply add a second file with the same namespace and class name to add any additional member.
Dino Esposito is Wintellect's ADO.NET and XML expert, and a trainer and consultant
based in Rome, Italy. Dino is a contributing editor to Windows Developer
Network and MSDN Magazine, and the author of several books for Microsoft
Press including Building Web Solutions with ASP.NET and ADO.NET
and Applied XML Programming for .NET. Contact Dino at [email protected].