-1

I am following an online tutorial to learn how to write a serial communicator.

I am using VS2019 and .Net 5.0, which is different from the environment used in the tutorial.

To use the SerialPort tool, I try to create :

        static SerialPort serialPort1;

as in the code:

using System;
using System.Windows.Forms;
using System.IO.Ports;

namespace SerialPortCommunication {
    public partial class Form1 : Form {

        static SerialPort serialPort1;
        public Form1() {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e) {
            string[] ports = System.IO.Ports.SerialPort.GetPortNames();
            comboBox1.Items.AddRange(ports);
            comboBox1.SelectedIndex = comboBox1.Items.Count > 0 ? 0 : -1;
        }

        private void button1_Click(object sender, EventArgs e) {
            if (button1.Text == "Open Port") {
                serialPort1.PortName = comboBox1.Text;
                serialPort1.Open();
                button1.Text = "Close Port";
            }
            else {
                serialPort1.Close();
                button1.Text = "Open Port";

            }
            
        }
    }
}

When I executed it , I encountered the System.NullReferenceException: 'Object reference not set to an instance of an object.'

But after I changed it to

static SerialPort serialPort1 = new SerialPort();

the VS doesn't show the Exception anymore.

My quesition is :

I have been told that we don't need and we can not create an instance for a static object, but in this case why do I need to create one instance to initialize the serialPort1?

I am confused...

As a beginner, I may have some unclear concepts. Could you provide me with some guidance or recommend some resources for me to study?

2 Answers2

2

That's correct: you can't create instances of static classes.

For example:

public static class Bob
{
    public void Test() => Console.WriteLine("hello");
}

var bob = new Bob(); // this won't compile
Bob.Test(); // this will because you're calling a static method

SerialPort is not a static class:

public class SerialPort : System.ComponentModel.Component

What you have is a static field:

static SerialPort serialPort1;

And you're assigning an instance of SerialPort to it:

serialPort1 = new SerialPort();

The only difference is that you're doing this at the same time as declaring the field:

static SerialPort serialPort1 = new SerialPort();

In short: you're not creating an instance of a static class, you're instantiating a static field with an instance of the non-static class SerialPort.

P.S. Please also note the difference between fields and properties if you're unaware of these concepts.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • 1
    Thank you for your response, it was very helpful in clarifying my understanding and now I know where I was mistaken! – PaperOrStone Apr 27 '23 at 04:29
0

SerialPort is a component from System.IO.Ports and is not a static class. you can define a serial port in csharp like this:

private System.IO.Ports.SerialPort serialPortRKE;

then you should set some settings like baudrate or PortName or ...

serialPortRKE.PortName = "COM3";
serialPortRKE.BaudRate = 9600;
serialPortRKE.DataBits = 8;
serialPortRKE.Handshake = Handshake.None;
serialPortRKE.Parity = Parity.Odd;

then based on your projects you can use DataReceived event or ...

this.serialPortRKE.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.serialPortRKE_DataReceived);

I think the CodeProject tutorial is very good: Serial Comms in C# for Beginners