Search code examples
c#if-statementsplitlinetranslate

"else" completes even if "if" is true


I'm messing with some kind of dictionary, that is supposed to translate words from one textbox to other, and the other way around, but It doesn't act as I'd like it to. The code for the button is:

private void button1_Click(object sender, EventArgs e)
    {
        string[] lines = File.ReadAllLines("C:/words.txt");
        int i = 0;
        var items = from line in lines
                    where i++ != 0
                    let words = line.Split('|')
                    where words.Count() > 1
                    select new
                    {
                        word = words[0],
                        translation = words[1]
                    };

        foreach (var item in items)
        {
            if (textBox1.Text == item.word)
            {
                textBox2.Text = item.translation;
            }
            if (textBox2.Text == item.translation)
            {
                textBox1.Text = item.word;
            }
            else
            {
                label3.Text = ("not found");
            }
        }
    }

Edit: Doesn't work with "else if" either.


Solution

  • I find it best to avoid if statements where possible, and I especially try to avoid else and else if. The reason for this is that it simply gets confusing when there are multiple conditions to try and follow. Here is possibly a cleaner way to understand what is going on and also solve your issue.

            foreach (var item in items)
            {
                if (textBox1.Text == item.word)
                {
                    textBox2.Text = item.translation;
                    continue;  // Don't process anything else in this loop.
                }
                if (textBox2.Text == item.translation)
                {
                    textBox1.Text = item.word;
                    continue;  // Don't process anything else in this loop.
                }
                label3.Text = ("not found");
            }
    

    Since we don't want any other logic to execute (my assumption) if one of our if statements is true, we simply use continue to skip the rest of the logic in the foreach and move to the next item.

    Why is this in a loop anyway? Won't the text in the first iteration be overwritten by subsequent iterations?