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


Jump to: navigation, search
CSharp-Online.NET:Tutorials
C# Tutorials

New Features in C# 2.0

© 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:

  • All partial type definitions must be modified with the partial keyword
and must belong to the same namespace and the same module and assembly.

  • The partial modifier can appear only before the class, interface,
and struct keywords.

  • Access modifiers (public, private, etc.) must match all the partial types of the same class.


Previous_Page_.gif Next_Page_.gif


Personal tools