add partial file to existing form file

user1903439 picture user1903439 · Feb 19, 2013 · Viewed 8.5k times · Source

I have a Window Form App project. At the moment all of my code is in Form1.cs file which is the default file. Now I have about 1300 lines of code in this single file. I want to break down this one file code into several files and I want to use the "partial" key word (I don't want to do anything drastic). So how should I add the files

Right click project name->add->new item ->class results into class1.cs, class2.cs and so on

But this file converts to a form form file after compilation. What's the correct way of adding so that the new file integrates with my existing project Form1.cs and Form1.cs[Design]?

Answer

Alex Filipovici picture Alex Filipovici · Feb 19, 2013

You have to keep the namespace, the class name and mark it with partial. The file name is not really important for it to work, but it's a good practice so that the developers can identify rapidly the contents of the file.

Form1.cs

namespace TheSameNamespace
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    }

    // other definitions
}

Form1.Designer.cs

namespace TheSameNamespace
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        // the rest of the designer class
    }
}

Form1.Calculations.cs

namespace TheSameNamespace
{
    partial class Form1
    {
        // calculation methods definitions
    }
}

Form1.EventHandlers.cs

namespace TheSameNamespace
{
    partial class Form1
    {
        // event handlers definitions
    }
}

and so on...