-1

I am trying to build an Arduino project to measure CPU and GPU temps through Open Hardware Monitor and now I have problem in C# application.

It gives this error on line 45:

A local variable named 'port' cannot be declared in this scope because it would give a different meaning to 'port', which is already used in a 'parent or current' scope to denote something else

Can I get some help? Thank you very much!

private void Init()
{
    try
    {
        notifyIcon1.Visible = false;
        port.Parity = Parity.None;
        port.StopBits = StopBits.One;
        port.DataBits = 8;
        port.Handshake = Handshake.None;
        port.RtsEnable = true;
        string[] ports = SerialPort.GetPortNames();
45      foreach (string port in ports)
        {
            comboBox1.Items.Add(port);
        }
        port.BaudRate = 9600;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Jaccob
  • 75
  • 2
  • 7
  • 1
    Just rename the variable in your `foreach` to something else as you clearly already have a variable with that name. – juharr Sep 08 '17 at 16:30
  • The error is quite clear. You have another variable called port somewhere. – OldProgrammer Sep 08 '17 at 16:30
  • You obviously already have a variable named `port`, you are using it already. So you cannot give the loop variable (in your `foreach`) the same name. The error message is pretty clear. – René Vogt Sep 08 '17 at 16:31
  • 3
    I am genuinely curious to know why this question is being down-voted. The question is clear and well formatted. I get that it is a seemingly trivial problem but the OP clearly doesn't understand how scoping works, or that a new variable is being declared in the `foreach`, or something. Why are they being punished for that? – Jason Boyd Sep 08 '17 at 16:37
  • @JasonBoyd there are tons of questions asking for exactly the same (ignoring variable name) error message. Presumably OP looked at those existing posts, but for question to be good quality for SO that research must be shown in the post. You also provided reasons why post should be closed as "unclear" or "too broad" as OP seem to have problem understanding on of the concepts mentioned in (very detailed) error message... – Alexei Levenkov Sep 08 '17 at 17:00

1 Answers1

2

You have a variable named port in your code already. So it doesn't allow you to declare it again in your foreach loop. Change it's name to something else:

foreach (string port2 in ports)
{
    comboBox1.Items.Add(port2);
}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • I would name the array `serialPortNames` and the foreach variable `serialPortName`, it's more descriptive – Sybren Sep 08 '17 at 16:34