1

i'm learning for myself c# in visual studio, so I have a error.

Field "MainWindow.port" is never assigned a value, so it will always have default value null.

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Ports;

namespace WpfApp15
{

    public partial class MainWindow : Window
    {
        SerialPort port;
        public MainWindow()
        {
            InitializeComponent();
            SerialPort port = new SerialPort();
            port.BaudRate = 9600;
            port.PortName = "COM4";
            port.Open();

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            port.WriteLine("1");
        }
    }
}
  • 1
    The first SerialPort variable is not the same variable inside the MainWindow code. They just have the same name but are two different objects. Inside the constructor you initialize the variable declared locally there, not the variable declared at the class level. Thus your code will fail with a NullReferenceException when you call the Button_Click that uses the class level variable. [What is a null reference exception and how do I avoid it](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Steve Aug 19 '17 at 15:55
  • Yes, as @Steve says this is because you have two `port` variables, and that is because of what we call `scopes`. Please learn more about them. You could Google, and here's a more [technical and detailed official document](https://msdn.microsoft.com/en-us/library/ms973875.aspx), and here's a good [SO answer](https://stackoverflow.com/a/1196965/302248). – Sach Aug 19 '17 at 15:58

1 Answers1

1

So this error occurs because you instantiate the wrong variable. Instead of instantiating the member variable port you did instantiate the local variable port which is out of scope in your method Button_Click. Change your code as follow:

public partial class MainWindow : Window
{
    SerialPort port;
    public MainWindow()
    {
        InitializeComponent();
        port = new SerialPort(); // removed SerialPort
        port.BaudRate = 9600;
        port.PortName = "COM4";
        port.Open();

    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        port.WriteLine("1");
    }
}