Home > Software design >  Is there a main method in C# analogous to C's int main()?
Is there a main method in C# analogous to C's int main()?

Time:09-17

I'm new to C sharp writing a program to read data from a serial port. I'm used to writing in C and admittedly do not have much experience with object oriented languages. I want a piece of code to run to open a serial port without having to be called, ie. it will run as if it's in the int main() in C. I have the code below to try to figure out my problem.

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;

namespace Nav_Monitor
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void t_tick(object sender, EventArgs e)
        {
            textBox1.Text  = Environment.NewLine;
            textBox1.Text  = DateTime.Now.ToString("hh:mm:ss tt");
        }

        SerialPort serialPort;
        private void openSerialPort(object sender, EventArgs e)
        {
            serialPort = new SerialPort("COM1", 19200, Parity.None, 8, StopBits.One);
            serialPort.Handshake = Handshake.None;
        }

    }
}

if I move the code outside of the method openSerialPort then I get an error 'the name "serialPort" does not exist in the current context'.

        serialPort = new SerialPort("COM1", 19200, Parity.None, 8, StopBits.One);
        serialPort.Handshake = Handshake.None;

        private void openSerialPort(object sender, EventArgs e)
        {

        }

So do I need something analogous to main() in C to run code automatically? It doesn't seem like I should put code in my program.cs file which seems to be the analogous place. I'm lost!

CodePudding user response:

The most analogous method is in fact inside Program.cs. Main() is the entry point for C# applications. However, you might consider kicking off any background work after the page has loaded or in the constructor if the work is non-blocking and can be run in the background.

I see you're working in Windows Forms, where the Form.Load event may be a good place to open your serial port.

  • Related