2
SMSCOMMS SMSEngine = new SMSCOMMS("COM6"); 

The code doesn't seem to take my argument of COM6 as a valid ref string.How can I solve this?

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)); } 

3 Answers 3

3

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) 
Sign up to request clarification or add additional context in comments.

Comments

2

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.

3 Comments

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.
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.
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.
1

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); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.