Another language feature added in C# 2.0 is partial classes. Partial classes are portions of a class that the compiler can combine to form a complete class. Although you could define two or more partial classes within the same file, the general purpose of a partial class is to allow the splitting of a class definition across multiple files. Primarily this is useful for tools that are generating or modifying code. With partial classes, the tools can work on a file separate from the one the developer is manually coding. C# 2.0 declares a partial class by appending the contextual keyword, partial, to the definition, as Listing 5.40 shows. Listing 5.40. Defining a Partial Class
In this case, each portion of Program is placed into a separate file, as identified by the comment. Besides their use with code generators, another common use of partial classes is to place any nested classes into their own files. This is in accordance with the coding convention that places each class definition within its own file. For example, Listing 5.41 places the Program.CommandLine class into a file separate from the core Program members. Listing 5.41. Defining a Nested Class in a Separate Partial Class
Partial classes do not allow extending compiled classes, classes in other assemblies. They are only a means of splitting a class implementation across multiple files within the same assembly. |