Partial Classes

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

 // File: Program1.cs partial class Program { } // File: Program2.cs partial class Program { } 

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

 // File: Program.cs partial class Program {   static void Main(string[] args)   {     CommandLine commandLine = new CommandLine(args);     switch (commandLine.Action)     {         // ...     }   } } // File: Program+CommandLine.cs partial class Program {    // Define a nested class for processing the command line.    private class CommandLine    {        // ...    } } 

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.

Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185 © 2008-2017.
If you may any questions please contact us: