[2.0] If statment with string
Hi all,
I am brand new to C# and I am trying to edit a program I have been given.
Basically I have a string and I want to see if it equals another string. I have this but it gives me the error: Error 1 Cannot implicitly convert type 'string' to 'bool'.
Code:
String SerialIn = System.Text.Encoding.ASCII.GetString(readBuffer,0,count);
if (SerialIn == 'OK')
{
}
Could someone give me a hand? I cannot seem to find anything like this do you do this another way in C# as I am use to vb.net.
Cheers,
Sam
Re: [2.0] If statment with string
Apart from the fact that code wouldn't compile because you have single quotes around OK, there's nothing wrong with that code. There's nothing there that would be causing that exception. I suggest that you look a bit closer and you'll likely find that the exception is being thrown elsewhere.
Re: [2.0] If statment with string
Oh yeh,
Sorry I tried that to see if it worked, I had "" originally.
I cannot seem to see any other errors, I suppose this error means you cannot convert string to boolean? Which is weird as SerialIn is set as string in the line above.
Is there anything you could think of?
This is the procedure:
Code:
private void ReadPort()
{
while (_keepReading)
{
if (_serialPort.IsOpen)
{
byte[] readBuffer = new byte[_serialPort.ReadBufferSize + 1];
try
{
int count = _serialPort.Read(readBuffer, 0, _serialPort.ReadBufferSize);
String SerialIn = System.Text.Encoding.ASCII.GetString(readBuffer,0,count);
if (SerialIn == "OK")
{
DataReceived(SerialIn);
}
else if (SerialIn == "Error")
{
}
}
catch (TimeoutException) { }
}
else
{
TimeSpan waitTime = new TimeSpan(0, 0, 0, 0, 50);
Thread.Sleep(waitTime);
}
}
}
Cheers,
Sam
Re: [2.0] If statment with string
Is the variable string different from String?
Sam
Re: [2.0] If statment with string
I just made a quick test on the lines of code you claim to have the error on and everything worked fine. Why don't you step through the code in the debugger and see where the error is happening and the value of everything pertaining to the error. It would seem that error would occur if you had = instead of == but you say you don't. Put a breakpoint on the error line and check the values of everything like I said and then see what happens.
Re: [2.0] If statment with string
string and String are not variables.
string is a type and String is a class. If you use string however I believe there is an implicit conversion to String when needed. I might be wrong though. That isn't your problem, however.