Partial Class Definitions


When you create classes with a lot of members of one type or another, things can get quite confusing, and code files can get very long. One thing that can help here, that you've looked at in earlier chapters, is to use code outlining. By defining regions in code, you can collapse and expand sections to make things easier to read. For example, you might have a class defined as follows:

 public class MyClass { #region Fields private int myInt; #endregion #region Constructor public MyClass() { myInt = 99; } #endregion #region Properties public int MyInt { get { return myInt; } set { myInt = value; } }  #endregion #region Methods public void DoSomething() { // Do something... } #endregion } 

Here, you can expand and contract fields, properties, the constructor, and methods for the class, allowing you to focus just on what you are interested in.

It is even possible to nest regions in this way, so some regions are only visible when the region that contains them is expanded.

However, even using this technique, things can still get out of hand. One alternative is to use partial class definitions. Put simply, you use partial class definitions to split the definition of a class across multiple files. You could, for example, put the fields, properties, and constructor in one file and the methods in another.

To do this, you just need to use the partial keyword with the class in each file that contains part of the definition, as follows:

 public partial class MyClass {    ... }

If you use partial class definitions, then this keyword must appear in this position in every file containing part of the definition.

Partial classes are used to great effect in Windows applications to hide the code relating to the layout of forms from you. You've already seen this in fact, back in Chapter 2. A Windows form, in a class called Form1 say, has code stored in both Form1.cs and Form1.Designer.cs. This enables you to concentrate on the functionality of your forms, without having to worry about your code being cluttered with information that doesn't really interest you.

One final note about partial classes: Interfaces applied to one partial class part apply to the whole class. This means that the following definitions are equivalent:

 public partial class MyClass : IMyInteface1 { ... } public partial class MyClass : IMyInteface2 { ... } 

and:

 public class MyClass : IMyInteface1, IMyInteface2 { ... } 
Note

This also applies to attributes, which you look at in Chapter 27.




Beginning Visual C# 2005
Beginning Visual C#supAND#174;/sup 2005
ISBN: B000N7ETVG
EAN: N/A
Year: 2005
Pages: 278

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