Page 1 of 1

Static constructor to get port name ???

PostPosted: Sun Oct 07, 2018 9:55 pm
by beefy
VS SCREENSHOT.png


This one has been kicking my ass.

I create a new SerialPort instance easy enough. However, I want to get the port name from a DRO instead of just writing it in the plugin code like this:
Code: Select all
SerialPort MyPort = new SerialPort("COM1");


I used the example plugin and made the changes shown in the screenshot. Wherever I added code I commented "// MY CHANGES".

As can be seen, I'm getting the red squiggly line under "UC", in the static constructor.

I used a static constructor because I read that it runs at the beginning of the class instanciation, before any class members are created, and therefore thought I could use that to get the port name from the DRO before the SerialPort object is created.

Obviously I'm doing something wrong.

Keith

Re: Static constructor to get port name ???

PostPosted: Mon Oct 08, 2018 9:41 am
by Dan911
Put in a method than call it.

Code: Select all
public void serialport()
 {

   SerialPort MyPort = new SerialPort();

    MyPort.PortName = UC.Getfield(true,3000);
    MyPort.BaudRate = Convert.ToInt32(UC.Getfield(true, 3001));// or MyPort.BaudRate = 9600;
    MyPort.Open();
    MyPort.Write("test");

  }

Re: Static constructor to get port name ???

PostPosted: Mon Oct 08, 2018 2:51 pm
by dezsoe
Keith,

Your problem is underlined on your picture. When the constructor is called, the UC variable has no value. You could read the DRO in the Init_event or in the Loop_event at the Firstrun section.

Re: Static constructor to get port name ???

PostPosted: Mon Oct 08, 2018 11:28 pm
by beefy
Thanks for the replies Dan & Dezsoe,

As suggested I ended up doing it in the "firstrun" method and seems good.

After some further Googling on the matter, it seems I was trying to call an "instance method" (UC.) from a static method (i.e. the static constructor), and this cannot be done in C#.

The error thrown was:
CS0120: An object reference is required for the nonstatic field, method, or property ............

Keith.

Re: Static constructor to get port name ???

PostPosted: Mon Oct 08, 2018 11:49 pm
by Dan911
You Beat me to the punch...Lol Yes UC. cannot be used in a static method, thought my example spoke for itself. Didn't bother giving other suggestions because wasn't sure what you were trying to achieve.

Dan