I'm trying to divide the code into files. Here is the heading of my class:

public class Form1 : Form 

In the second file I write:

 public partial class Form1 : Form 

Everything works, but in Solution Explorer this file is displayed as a form (for sure because Windows.Forms is connected). I just wanted the code, but what is this, is this normal?

    3 answers 3

    Yes, this is normal: after all, everything is one and the same class.

    I recommend paying attention to this.

    If there is a lot of code and start dividing the class into several listings through partial, then it’s time to think about refactoring and putting part of the business logic into separate classes.

    And already for new classes, select when inserting the type Class , and not the Windows Form :

    Add new item

      Yes, you can make the correct display of your additional file as a file with code.

      After creating this file (I called it Form1Ext.cs), build the project.

      Upload project: right click on project in Solution Explorer> Unload Project.

      Open the {ProjectName} .csproj file in your project folder using any text editor (Notepad). Find the line there

       <Compile Include="Form1Ext.cs"> 

      Of course, look for the name of your file.

      Replace nested node

       <SubType>Form</SubType> 

      per node

       <DependentUpon>Form1.cs</DependentUpon> 

      Save the * .csproj file. You can close the text editor.

      Download the project: PCM on the project> Reload Project.

      I got the following display in Solution Explorer:

      form code attachment file

      • I put a plus, because you also need to know about this method, but it’s still better to produce smaller hacks and pay more attention to clean code. - AK
      • one
        @AK - yes, I agree that it is better not to use such a trick. - Alexander Petrov

      And I would say that it is not necessary to divide the form class into parts. The main reason is a visual editor. According to my (long-term) experience, I can say that Visual Studio does not digest such things as splitting a form into parts, and inheritance too. The fact that you have in the Solution Explorer does not appear as you want - it's more flowers. But when you can’t (completely) open the editor, then everything, to rule only with your hands, which will greatly affect your productivity.

      Therefore recommendations:

      • Do not use inheritance on forms, do not divide into partial classes.
      • Allocate functionality related to computing, accessing data in separate classes.
      • Select the same type of visual blocks into separate User Controls.