New Features in C# 2.0—Partial Types: How do I do that?
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:Tutorials |
| C# Tutorials |
| © 2005 O'Reilly Media, Inc. |
How do I do that?
The easiest way to see partial types at work is to examine the previous
example (AnonymousMethods). Examine the declaration of the class in
Form1.cs:
partial class Form1 : Form { public Form1() { InitializeComponent( ); this.button1.Click += delegate { label1.Text = "Goodbye"; }; } // private void button1_Click // (object sender, EventArgs e) // { // label1.Text = "Goodbye"; // } }
The partial keyword indicates that the code in this file does not necessarily
represent the complete definition of this class. In fact, you saw earlier
that the Visual Studio 2005 designer generated a second file, Form1.
Designer.cs, which contains the rest of the definition:
namespace AnonymousMethods { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose( ); } base.Dispose(disposing); } #region Windows Form Designer generated code /// Designer-generated initialization code ... #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Button button1; } }
Together, these two files completely define the Form1 class, but you are
spared dealing with the designer-generated code unless you need to
work with it. This makes for simpler and cleaner development.
There is some "fine print" you need to be aware of in regard to using partial classes:
and must belong to the same namespace and the same module and assembly.
- All partial type definitions must be modified with the
partialkeyword
and
- The
partialmodifier can appear only before theclass,interface,structkeywords.
- Access modifiers (
public,private, etc.) must match all the partial types of the same class.
|

