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
csharp
partial class NetworkForm
{
MenuStrip menuStrip1;
// ...
void InitializeComponent()
{
ComponentResourceManager resources =
new ComponentResourceManager(typeof(NetworkForm));
this.menuStrip1 = new MenuStrip();
this.SuspendLayout();
// ...
this.ResumeLayout(false);
this.PerformLayout();
}
}
partial class NetworkForm : Form
{
public NetworkForm()
{
InitializeComponent();
}
}csharp
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
- All parts must be in the same assembly and are merged into a single type at compile time
- Common sources of code generation are:
- WinForms designer
.Designer.csfiles that construct a desktop user interface - Entity Framework's EDMX
.Designer.csor T4-generated entity classes containing properties and mappings based upon a database
- WinForms designer