I'm pretty new with C#, and I was wondering if it would be possible to move parts of code (from my main Form) to an external .cs file (still in the same solution), with the same level of access to variables and functions from my form1.cs file, as my original form1.cs file.
I'm working with the latest version of the .NET-framework and I have no other references to (external) code.
Here is a simple example of what I'm looking for:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Code1
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
// variables
text1 = "Hello"
public void ExternalCode()
{
this.BackgroundImage = null;
Btn1.Text = "Click me";
Lbl1.Text = text1;
}
private void Btn1_Click(object sender, EventArgs e)
{
ExternalCode();
}
}
}
This form only has a button named "Btn1" and a label named "Lbl1" in it.
I would like the code inside the method SeparateCode to be in a separate file, but still with the ability to access the variables and controls from Form3, and for Form3 to still be able to execute the method in the external file (ExternalCode).
I thought of making this file a daughter of the Form3.cs, but as I said, I'm still pretty new at this so I don't really know how to.
partialkeyword there. So create a separate .cs file, that uses the same namespace, and also haspublic partial class Form3(you don't need to specify that it inherits fromForm, as that has already been done), and then move yourSeparateCodemethod to this new file. The compiler will treat these two files as "the same class" and compile them as though you had all the code in just one file.