Click here to Skip to main content
15,908,020 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I want to use variable x in another class


C#
public partial class Form1 : Form
   {
       static SerialPort _serialPort;

       ....
       }


What I have tried:

C#
public partial class Form1 : Form
    {
        static SerialPort _serialPort;

        public Form1()
        {
            InitializeComponent();
        }
        private void ConfigurarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Config_Serial janela2 = new Config_Serial(this);
            janela2.ShowDialog();
        }


but when I write "janela1. ? don't have the _serialPort option why?



C#
public partial class Config_Serial : Form
    {
        Form1 janela1;
        string[] portas = { "" };




        public Config_Serial(Form1 x)
        {
            InitializeComponent();
            janela1 = x;
            janela1.?  does not appear _serialPort
        }
Posted
Updated 3-Oct-19 3:21am

I suggest you define all the operations related to establishing, maintaining, and raising events related to the use of the serial port in one static class. Use Public Properties to expose access to data/buffers, etc. Expose serial port events to external classes by delegates, like 'Action and 'Func.

There are many public libraries for serial port interop with C#: [^]. Check them out.

Here's a CP article many found useful: [^]
 
Share this answer
 
v2
janela1 is an instance of the type Form1, however static methods are defined on the type itself, not on instances of that type. So your code should be

C#
Form1._serialPort


Note that as the variable is on the type itself, all your classes will share whatever _serialPort is as there is only one Form1 type, so make sure that's what you want.
 
Share this answer
 
v2
You need to declare your field as public. See Access Modifiers - C# Programming Guide | Microsoft Docs[^]. Fields and other members are implicitly private, unless you define different access modifier.

Also, you may want to consider using property instead of field. See Properties - C# Programming Guide | Microsoft Docs[^] for more information.
 
Share this answer
 
Comments
Gilcecler Carneiro 3-Oct-19 8:52am    
@jimmson I'll read
In contrast to what other people have said on this topic, DO NOT EXPOSE YOUR CLASS VARIABLES AND FIELDS AS PUBLIC!

One class/form should never know about the internal workings of another class/form. Your Config_Serial form should expose public methods and properties to manipulate the data model the Config_Serial form is maintaining.
 
Share this answer
 
Comments
Gilcecler Carneiro 3-Oct-19 8:53am    
thanks. I will change and publish again

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900