Danijel Milosevic
Danijel Milosevic

Reputation: 21

C# Comparing 2 strings always return false

I'm trying to make the program respond to certain words sent by a microcontroller, but when I compare the received word with a pre-defined word, it always returns false.

private void ReadData()
{
    if (serialPort1.IsOpen == true)
    {
        if (serialPort1.BytesToRead > 0)
        {
            string readBuffer = serialPort1.ReadLine(); 

            textBox2.Text = readBuffer;
            if (readBuffer.Equals("A")) //MY MAIN PROBLEM
            {
                textBox2.Text += "YEP";
            }
            else
            {
                textBox2.Text += "NOPE";
            }
        }
    }
}

Basically when the microcontroller sends letter "A", it reads it and stores it into the readBuffer string, and even prints it out in a textbox(textBox2). My result is always ANOPE in the textbox (A is what the microcontroller sent and NOPE is always there because the if failed). I started C# recently and lost several days trying to figure this one out, but I really can't seem to find a solution to an apparently simple issue.

Upvotes: 1

Views: 703

Answers (2)

Danijel Milosevic
Danijel Milosevic

Reputation: 21

Thanks to Willem Van Onsem and René Vogt I figured out the problem. After it reads the data and stores it into the readBuffer, it also includes \r (carriage return), making the string actually "A\r", which is why it was always false compared to "A".

Upvotes: 1

rogerwamba
rogerwamba

Reputation: 72

Two things I submit to you:
1. Things are not always as they appear: use readBuffer.Trim().Equals("A") instead.

  1. readBuffer.Equals("A") performs an ordinal (case-sensitive and culture-insensitive) comparison.
    A = A but A ≠ a if you use .Equals to compare them.

So in final analysis, try this:
if (readBuffer.Trim().ToUpper().Equals("A"))

Upvotes: 0

Related Questions