Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If / else statements in C#

enter image description here

Why does this work?

    private void button1_Click(object sender, EventArgs e)
    {
        if (!checkBox1.Checked)
        {
            MessageBox.Show("The box is not checked!");
        }
        if (checkBox1.Checked == true)
        {
            if (label1.BackColor == Color.Red)
            {
                label1.BackColor = Color.Blue;
            }
            else
            {
                label1.BackColor = Color.Red;
            }
        }
    }

But this doesn't?

   private void button1_Click(object sender, EventArgs e)
    {
        if (!checkBox1.Checked)
        {
            MessageBox.Show("The box is not checked!");
        }
        if (checkBox1.Checked == true)
        {
            if (label1.BackColor == Color.Red)
            {
                label1.BackColor = Color.Blue;
            }
            if (label1.BackColor == Color.Blue)
            {
                label1.BackColor = Color.Red;
            }
        }
    }

I would think that the compliler would read the lines each time I press the button so it should not be any different to have two if statements after each other.

like image 581
somethingSomething Avatar asked Sep 14 '25 03:09

somethingSomething


1 Answers

You are changing to blue if it was red and then your are changing it to red if it was blue. Basically first if first if will change it to blue then second if will change it back to red. It works this way because instructions are executed sequentially, so your second if is always checked after your first if. Just use else if so second if won't work if first one fired:

// if red then change to blue
if (label1.BackColor == Color.Red)
{
    label1.BackColor = Color.Blue;
}
// otherwise, if blue then change to red
// this condition will be checked if first "if" was false
else if (label1.BackColor == Color.Blue)
{
    label1.BackColor = Color.Red;
}
like image 170
Zbigniew Avatar answered Sep 16 '25 18:09

Zbigniew