Skip to content

Partial types C# 2.0code generation

Split classes between files to keep code generated away from code written.

It can be advantageous to split a class into multiple files.

One common scenario is generating code into a different file so it does not overwrite developer-written code, for example in WinForms designers or Entity Framework generated classes.

Code

C#
partial class NetworkForm
{
    MenuStrip menuStrip1;
    // ...

    void InitializeComponent()
    {
        ComponentResourceManager resources =
            new ComponentResourceManager(typeof(NetworkFormBase));
        this.menuStrip1 = new MenuStrip();
        this.SuspendLayout();
        // ...
        this.ResumeLayout(false);
        this.PerformLayout();
    }
}

partial class NetworkForm : Form
{
	public NetworkForm()
    {
        InitializeComponent();
    }
}
C#
class NetworkFormBase : Form
{
    MenuStrip menuStrip1;
    // ...

	public NetworkFormBase()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        ComponentResourceManager resources =
            new ComponentResourceManager(typeof(NetworkFormBase));
        this.menuStrip1 = new MenuStrip();
        this.SuspendLayout();
        // ...
        this.ResumeLayout(false);
        this.PerformLayout();
    }
}

class NetworkForm : NetworkFormBase
{
	public NetworkForm() : base()
    {
        // User code
    }
}

Notes

Common sources of code generation are:

  • WinForms designer .designer.cs files that constructs a desktop user interface
  • Entity Framework's .generated.cs files containing properties and mappings based upon a database

More information