Answered Split the main form into smaller files

MakeItWork

Member
Joined
Feb 20, 2021
Messages
6
Programming Experience
1-3
Hi all,

Hopefully this question is not to stupid so here we go.....
With c# window forms the main code starts with

public partial class Form1 : Form

I have been splitting the main code file into separate files that still compile into one with

public partial class Form1

It works but does not appear to like any other visual studio than the one it was set up in and the project file can corrupt easy.
I think it is the cause of other problems like Graphics .invalidate which has never worked. Windows size adjustment of the program being run does not change to the value it is set to. Int16 (short) conversion/use has caused errors with nothing wrong with the code. Picturebox code would not work (no compile errors) until it was moved to another location, nothing wrong with its original location and now graphics code doing the same.

I Googled the problem which gives no end on how to split classes, it is not clear how to split the main form.

How wrong is splitting code up using public partial class Form1 and what is the correct way.

Thanks in advance
 
Solution
As you can see in documentation inheritance and implemented interfaces are merged, you don't have to repeat this information in each file, and you can spread it across the files (see the article for example).

Don't try to design the partial files except the default one, or else designer will attempt to add designer code twice, which won't work. If you for example try to add a control to the extra partial class the designer adds InitializeComponent and more that conflicts.
Change the filename of added partial files to Form1.yourNameHere.cs

This stops the problem with a design window being attached to each added partial file.
Microsoft have in there wisdom made all added partial main code...

Sheepings

Well-known member
Joined
Sep 5, 2018
Messages
2,038
Programming Experience
10+
I can't believe I actually approved this topic. :LOL:

Well, I'm looking forward to the replies. lol

And, welcome to the forums.
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
3,122
Location
Chesapeake, VA
Programming Experience
10+
Except for the problem about Visual Studio WinForms Designer having issues with splitting up the form code into multiple files, all your other problems have nothing to do with splitting the files. Consider the fact that by default Visual Studio already used partial classes to separate your code from the designer generated code in the Form.Designer.cs file. People have successfully used WinForms for years with that file configuration. I suspect those other problems are due to bugs in your code, or not fully understanding how some things work.

Personally, I don't use the WinForms Designer, so it doesn't matter that I use partial classes often without ill effects. On the other hand, I rarely have to split up my Form class into multiple files because I apply the MVC or MVP pattern to my code. So my Form code (aka View) tends to be just thin layers that call the Model and/or the Controller or Presenter.

Why don't you show us some of the code that you are running into problems with and we can try to get you sorted out.
 

Sheepings

Well-known member
Joined
Sep 5, 2018
Messages
2,038
Programming Experience
10+
Is there actually a logical reason for doing this? 🤔

And if there is, when would you want to?

I here you all the way regarding the designer code. Me and you have been on that same page now for many years.
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
3,122
Location
Chesapeake, VA
Programming Experience
10+
Yes, there are some logical reasons to do this, but usually it is when you are creating a new control from the ground up, not when you are writing a form -- unless the form doesn't follow the Single Responsibility Principle.

Anyway, check out the source code for the DataGridView control on Reference Source to see a control that has been split up into multiple files. As I recall, each file followed the SRP, but due to the constraints of WinForms, all that had to live within a single class.
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,792
Location
Sydney, Australia
Programming Experience
10+
The WinForms designer will expect two partial class files. Form1.cs is where it will create event handlers that you generate from the Properties window and Form1.Designer.cs is where it will declare, create and configure controls and components you add in the designer. As long as those two files are present with a partial Form1 declaration in them, the designer is happy. Other than that, you can add as many other code files with partial Form1 declarations in them as you like and they will all function as a single class. I've tested this and it seems to work without issue, but I obviously haven't tested every possible combination.

As you should ALWAYS do, you need to show us the code. You should provide the minimum amount of code necessary for us to understand and reproduce the issue. If we see the code then we can see what you may have done wrong and, if you haven't, see whether we get the same aberrant behaviour using the same code.
 

Sheepings

Well-known member
Joined
Sep 5, 2018
Messages
2,038
Programming Experience
10+
By all means single me out here.

But there are very very very few valid reasons for doing something like that. I honestly was anticipating more scepticism from senior devs here.

And I can't help but feel doing something like this is quite illogical???
 

Sheepings

Well-known member
Joined
Sep 5, 2018
Messages
2,038
Programming Experience
10+
For ASP.Net or something, yea, I can see the point of partial views, and segregating views but I don't see the need when it comes to Winforms.
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,792
Location
Sydney, Australia
Programming Experience
10+
By all means single me out here.

But there are very very very few valid reasons for doing something like that. I honestly was anticipating more scepticism from senior devs here.

And I can't help but feel doing something like this is quite illogical???
Personally, pretty much the only time I use partial classes is when I want part of the code to be auto-generated and part of the code to be user-editable, much like the split between designer code and user code in a form. For instance, I've just been updating our CodeGen tool at work for .NET 5.0 and EF Code First. We use this tool to generate various sets of files where there is one per entity, including DTOs and services. The service definitions are always in partial classes because we have a standard set of methods that get auto-generated in one partial class and we can add entity-specific methods in a second partial class.

If you have a class that contains a lot of code then regions should probably be the first option for grouping code relating to a specific area of functionality but partial classes might be a good option if the volume of code is very large. The DataGridView example from before is one such but I would suggest that most classes, be they forms or otherwise, that contain enough code to make partial classes a good option are probably poorly designed and out to be split into multiple distinct classes anyway.

That said, we can't all learn everything at once and coming to terms with the current issue may help the OP learn something else, given that they believe that partial classes are causing other issues that they definitely should not be.
 

MakeItWork

Member
Joined
Feb 20, 2021
Messages
6
Programming Experience
1-3
I was expecting this to be more or less straight forward lol.
Yea, what i am thinking is the same as in C++ with separate files, this makes editing and organising your code easier, it stops one file becoming large in size. I suspect it is easy to do when you know how.

I find microcontroller assembler simple and straight forward and i am learning c# with the same approach by avoiding a lot of the correct terminology and stuff i don`t think i need to know....trying to keep it simple, does that show? Lol. c# is a bit of fun like doing a crossword puzzle and usefull if i need to write software to interface a electronic project.

The only way to give a example is upload the entire project file, the file almost certainly will not load into any other editor (uses vs2019) becouse of the way the files have been separated but we shall see. Any thoughts/advice before i upload?

"Sheeping" "I honestly was anticipating more scepticism from senior devs here.", i am trying to make the code easier to read and edit by splitting a large file into smaller files, same as you can in C++, what do you think i am trying to do???
 

Sheepings

Well-known member
Joined
Sep 5, 2018
Messages
2,038
Programming Experience
10+
I know what you are trying to do. I just don't see the logic in the way of how you are going about it, and especially in Winforms.

And C++ is not C# either.

As I've often seen in the past, Skydiver telling people to ditch what they know in the way of C++ when moving to do things in C#.
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
3,122
Location
Chesapeake, VA
Programming Experience
10+
I suspect that @Sheeping's expectation was based on most senior devs would not let a single class grow that large that if would need to be split into multiple files to help the humans organize the contents of the class better.

When I do code reviews for peers, if the file size exceeds 600 lines, it is a code smell for me that perhaps the class within the file may not be following the SRP, and so should be broken up to make use of separate helper classes which can then be tested independently.

And yes, implementing object oriented programming in C++ is slightly different than implementing object oriented programming in C# because of different idiomatic uses, and different expectations for each language.
 

Sheepings

Well-known member
Joined
Sep 5, 2018
Messages
2,038
Programming Experience
10+
I can't preach about rules/principles and laws which should be kept, and then go off and break them myself. That's just stupid and hypocritical of me.

The other day I binned an entire application because a helper class exceeded 800 lines. Once again Skydiver makes a good point about SRP, and how you should apply it when writing an app. Regarding your initial issue, I wouldn't look any further than post 9, on the very last line.

Frankly, if you are writing a to a file that requires that a class must have a lot of functions, methods, or a very long and elaborate task/operation to execute, then you are likely not writing efficient code. Code that should have one single purpose to fulfil.
 

MakeItWork

Member
Joined
Feb 20, 2021
Messages
6
Programming Experience
1-3
Hi everyone, i would like to start again with a different approach as i feel there is a simple answer to this, i may be wrong of course.

We have a simplified code example below, it is only to show what i want it will not run.

C#:
using System;



namespace game

{

    public partial class Form1 : Form
    {
    //All your normal code when you double click on the design window in c# dotnet framework
    }

// Here we will put in some code, a function called PicBox, for example only.

       public void PicBox()
        {
            PictureBox[] picture = new PictureBox[(picRow * picCol)];
            int i;
            for (i = 0; i < picCol * picRow; i++)//(picRow * picCol); i++)
            {
                picture = new PictureBox();
                picture.BackColor = Color.Black;
                this.Controls.Add(picture);
                picture.Click += this.pb1_MouseClick;
                picture.SizeMode = PictureBoxSizeMode.StretchImage;
                picture.Visible = true;
            }
            picbox = picture;
    }

I would like to put the function PicBox into a seperate file, a separate window in visual studio that only needs to be clicked on if i want to edit the function PicBox, this is to help reduce clutter and make the code neater for me, basically it makes me happy.

To select a new class file in VS is ok for some types of code but to access windows functions can sometimes be more work than it is worth or not possible, i think i am correct in saying that.

I think i need to extend the first line of code given in a new project which is:
public partial class Form1 : Form

I am missing some of the basic understanding here.

If anything is not clear please ask, i am sure there is a simple answer to this.

Thanks in advance
 
Last edited by a moderator:

MakeItWork

Member
Joined
Feb 20, 2021
Messages
6
Programming Experience
1-3
To split the c# main code file is simple by the looks of it

public partial class Form1
{
}

The code i wrote in the first post appears not to be wrong, so the project file corruption problem and run errors i am having is caused by something else.

The project file creates a design window, a form1 for every partial file you have on any VS other than the one in current use, you do not have to run it. If one of the windows/partial files are closed on a "working" project to open it again in the solution explorer brings up a design window with your partial file. The new design window/form1 created with each of your partial files conflicts with the projects original. What could be the cause?

some information found on the net that may help others:

public partial class Form1 : Form By using partial it is possible to write the definition of same class in two different source file in the same namespace.It will be treated as same during compilation.You can find a class with same name Form1 in your project which is created automatically.

Form1 is the name of the Form and : is used to inherit the properties of base class . Here Form represents System.Windows.Forms.Form. We are inheriting to access the properties and methods of base class.
 
Last edited:

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
3,122
Location
Chesapeake, VA
Programming Experience
10+
How and when is the PicBox() method invoked by the Form1 class? It shouldn't matter if PicBox() lives in Form1.cs or in PicBox.Form1.cs. If it works while it lives in Form1.cs, it should continue to work in PicBox.Form1.cs. If it doesn't even work in Form1.cs, then it doesn't matter if it got moved to PicBox.Form1.cs.
 

MakeItWork

Member
Joined
Feb 20, 2021
Messages
6
Programming Experience
1-3
How and when is the PicBox() method invoked by the Form1 class? It shouldn't matter if PicBox() lives in Form1.cs or in PicBox.Form1.cs. If it works while it lives in Form1.cs, it should continue to work in PicBox.Form1.cs. If it doesn't even work in Form1.cs, then it doesn't matter if it got moved to PicBox.Form1.cs.
Skydiver the code is not called it is clearly described in the text what the code shows you lol, it says it is not actual working code, it shows you what i was asking for, not to demonstrate a working program it is all clearly written in the post, ya gotta laugh huh? I can make it work, there is no point as i say it demonstrates how i wanted to move code to a separate file, to make the code neater ect (all has been described already) in the most simplistic way i can. I could move on and go through the rest of your comments but they are covered in the post you have read and my last post shows i have already answered my own question anyway LOL making it even more pointless, i am bored so this forum does provide a little entertainment. Cheers anyways, any idea whats up with VS as described in my last post?
 

Sheepings

Well-known member
Joined
Sep 5, 2018
Messages
2,038
Programming Experience
10+
The compiler doesn't care what files are in the project, and they will be compiled if included in the projects configuration, providing your code matches up as it was wrote.
Anyway, why are you trying to adapt your C++ habits in a C# app?
 

MakeItWork

Member
Joined
Feb 20, 2021
Messages
6
Programming Experience
1-3
The compiler doesn't care what files are in the project, and they will be compiled if included in the projects configuration, providing your code matches up as it was wrote.
Anyway, why are you trying to adapt your C++ habits in a C# app?
Sheepings microsoft have put the partial file feature into c# and they have made this available for the main form code, i want to use this feature that microsoft have put in becouse it makes code neater for me, i like it and it is easy to use when you know how. I do not like C++, it is a over complicated mess in my opinion which is why i use c# it is far from perfect but a better option. I am not trying to bring any c++ habits to c#. Maybe you don`t like (hate?) the partial file feature? You don`t have to use it you know, just don`t answer threads on this subject....leave it mate. There is no need to answer anything i say...just leave it mate.

Anyway hi there,

I asked how do split up c# main code file, well, by finding the correct keywords and using google the truth is out there.

You split up the main code with:

public partial class Form1

Now here is the other bit you need to know:

Change the filename of added partial files to Form1.yourNameHere.cs

This stops the problem with a design window being attached to each added partial file.
Microsoft have in there wisdom made all added partial main code files without the usual editor support, all the text remains white, so it is just store your finished code and compile, if you find it needs a edit just cut and paste whatever you need back, so no big problem.

That now leaves the run errors if they still remain. There will be no point in posting anything here, it is a waste of time i now expect no usefull answer whatsoever because that is what i have received.

This thread is done no more posts thanks.
 
Last edited:
Top Bottom