Partial Class Definitions


Beginning with C# 2.0, a class definition can be broken into two or more pieces, with each piece residing in a separate file. This is accomplished through the use of the partial keyword. When your program is compiled, the pieces of the class are united, forming a single class.

The partial modifier has this general form:

 partial class classname { // ...

Here, classname is the name of the class that is being split into pieces. Each part of a partial class must be modified by partial.

Here is an example that divides a simple XY coordinate class into three separate files. The first file is shown here:

 partial class XY {   public XY(int a, int b) {     x = a;     y = b;   } }

The second file is shown next:

 partial class XY {   int x;   public int X {     get { return x; }     set { x = value; }   } }

The third file is

 partial class XY {   int y;   public int Y {     get { return y; }     set { y = value; }   } }

The following file demonstrates the use of XY:

 // Demonstrate partial class definitions. using System; class Test {   public static void Main() {     XY xy = new XY(1, 2);     Console.WriteLine(xy.X + "," + xy.Y);   } }

To use XY, all files must be included in the compilation. For example, assuming the XY files are called xy1.cs, xy2.cs, and xy3.cs, and that the Test class is contained in a file called test.cs, then to compile Test, use the following command line:

 csc test.cs xy1.cs xy2.cs xy3.cs

Two other points. First, it is legal to have partial generic classes. However, the type parameters of each partial declaration must match the other parts. Second, you can also create partial interface and structure definitions.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net