fiftyplus
fiftyplus

Reputation: 561

C#, member and variable scope

Relates to the problem Adding event handler in main() for SerialPort

After I change the mycomport to one of the member of the class, why I cant use it in main?

a busy cat http://img11.imageshack.us/img11/3664/49512217.png

namespace serialport
{
public class Program
{


    #region Manager Variables
    //property variables
    private string _baudRate = string.Empty;
    private string _parity = string.Empty;
    private string _stopBits = string.Empty;
    private string _dataBits = string.Empty;
    private string _portName = string.Empty;
    private RichTextBox _displayWindow;
    //global manager variables
    //private Color[] MessageColor = { Color.Blue, Color.Green, Color.Black, Color.Orange, Color.Red };
    internal List<Byte> portBuffer = new List<Byte>(1024);
    private SerialPort myComPort = new SerialPort();
    #endregion



    #region Manager Constructors
    /// <summary>
    /// Comstructor to set the properties of our
    /// serial port communicator to nothing
    /// </summary>
    public Program()
    {
        _baudRate = string.Empty;
        _parity = string.Empty;
        _stopBits = string.Empty;
        _dataBits = string.Empty;
        _portName = "COM1";
        _displayWindow = null;
        //add event handler
        myComPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
    }
    #endregion

    static void Main()
    {

        Program myProgram = new Program();
        //1. find available COM port
        string[] nameArray = null;
        string myComPortName = null;
        nameArray = SerialPort.GetPortNames();
        if (nameArray.GetUpperBound(0) >= 0)
        {
            myComPortName = nameArray[0];
        }
        else
        {
            Console.WriteLine("Error");
            return;
        }


        //2. create a serialport object
        // the port object is closed automatically by use using()
        myComPort.PortName = myComPortName;
        //the default paramit are 9600,no parity,one stop bit, and no flow control



        //3.open the port
        try
        {
            myComPort.Open();
        }
        catch (UnauthorizedAccessException ex)
        {
            MessageBox.Show(ex.Message);
        }
        //Add timeout, p161

        //reading Bytes
        byte[] byteBuffer = new byte[10];
        Int32 count;
        Int32 numberOfReceivedBytes;
        myComPort.Read(byteBuffer, 0, 9);
        for (count = 0; count <= 3; count++)
        {
            Console.WriteLine(byteBuffer[count].ToString());
        }


    }
    //The event handler should be static??
    internal void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        int numberOfBytesToRead;
        numberOfBytesToRead = myComPort.BytesToRead;
        byte[] newReceivedData = new byte[numberOfBytesToRead];
        myComPort.Read(newReceivedData, 0, numberOfBytesToRead);
        portBuffer.AddRange(newReceivedData);
        ProcessData();
    }
    private void ProcessData()
    {
        //when 8 bytes have arrived, display then and remove them from the buffer
        int count;
        int numberOfBytesToRead = 8;

        if (portBuffer.Count >= numberOfBytesToRead)
        {
            for (count = 0; count < numberOfBytesToRead; count++)
            {
                Console.WriteLine((char)(portBuffer[count]));
            }
            portBuffer.RemoveRange(0, numberOfBytesToRead);
        }
    }

}

}

Upvotes: 0

Views: 457

Answers (3)

Chris Shain
Chris Shain

Reputation: 51369

Because main is static, and now your variable isn't.

Instance variables and methods are associated with a particular instance of a class- one you have new'd.

Static variables and methods are associated with the class type, not any particular instance.

If I have the following:

public class Car {
    public int Speed { get; set; }

    public static main(string[] args) {
        Car a = new Car();
        Car b = new Car();

        // This is fine:
        var aSpeed = a.Speed;

        // This doesn't make sense (and doesn't compile)
        // Are we talking about a's speed?  b's speed?  Some other car's speed?
        var someSpeed = Speed;

    }

}

Upvotes: 0

jason
jason

Reputation: 241741

Because Main is declared as static but you are trying to access private instance fields. That's a no go, they are only accessible from methods in the same class.

The error message even tells you that. It says:

An object reference is required for the non-static field, method, or property....

An "object reference" means that you need an instance.

Upvotes: 0

user596075
user596075

Reputation:

Because Main() is a static method. Instance fields cannot be accessed directly by static methods. A static method would have to create an instance of the object or get an instance of the object passed to it for that to be possible.

Upvotes: 1

Related Questions