tags:

views:

60

answers:

3

Is this a valid value for this c# class default constructor,

public class SMSCOMMS
{
   public SMSCOMMS(ref string COMMPORT)
   {
    SMSPort = new SerialPort();
    SMSPort.PortName = COMMPORT;
    SMSPort.BaudRate = 9600;
    SMSPort.Parity = Parity.None;
    SMSPort.DataBits = 8;
    SMSPort.StopBits = StopBits.One;
    SMSPort.Handshake = Handshake.RequestToSend;
    SMSPort.DtrEnable = true;
    SMSPort.RtsEnable = true;
    SMSPort.NewLine = System.Environment.NewLine;
    ReadThread = new Thread(
        new System.Threading.ThreadStart(ReadPort));
}

and i am passing this value,

SMSCOMMS SMSEngine = new SMSCOMMS("COM6"); but it doesn't seem to take "COM6" as a valid ref string... Any suggestion..

+3  A: 

You can't pass a temporary with ref, because the called method must be able to assign to the caller's variable. Why are you using it to begin with? You never assign to COMMPORT.

Why not just:

public SMSCOMMS(string COMMPORT)
Matthew Flaschen
+2  A: 

There's no need to pass a ref param unless you're intending to modify the actual variable the caller's passed. Since you can't modify a string literal (it's constant, by definition), it's not valid for passing by reference.

cHao
Wrong. You can use `ref` with strings, and there are cases when you want to. If the method assigns to the `ref` variable, the caller now has a reference to a different string in their own variable.
Matthew Flaschen
I didn't say string -- i said string *literal*. If you know of a way to modify a string literal, let the .net people know about it, cause it's probably a bug. By definition, literals are constant. "a" will never be anything but "a". Though it could be replaced by another string, that is not the same thing as modifying the string itself.
cHao
Add to that, the code in question obviously was passing a string literal, not a variable (read: *there's no variable to assign to*), which i *thought* was obvious, and you have the reason stuff broke.
cHao
Sorry, I misread your post.
Matthew Flaschen
+1  A: 

You can only use ref when you are passing something that has a usable reference. That means you have to declare a variable first, then pass that variable by ref:

string comm = "COM6";
SMSCOMMS SMSEngine = new SMSCOMMS(ref comm);
jrista