If / else statements in C#

12,162

Solution 1

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

Solution 2

Why second snippet do not work.

Because in second snippet both if statements are independent. After color turns blue from first if, the second if gets called and changes its color back to Red. You need an else if

        if (label1.BackColor == Color.Red)
        {
            label1.BackColor = Color.Blue;
        }
        else if (label1.BackColor == Color.Blue)
        {
            label1.BackColor = Color.Red;
        }

Solution 3

This is a logic problem, here is an example of why it doesn't work:

// label is blue at this point
if (label1.BackColor == Color.Blue)
{
    // we change the colour to red
}
// label is red at this point
if (label1.BackColor == Color.Red)
{
    // we change it back to blue
}

The difference between the statements are the first uses else which changes the logic flow so you are only ever dealing with 1 scenario at a time (it's either Red or Blue). However, in the second as they are 2 separate statements you are dealing with both scenarios consecutively. There are a couple of resolutions to this, the most obvious (and probably the best) is to use the else like you are already. However, you could also use a switch:

switch (label1.BackColor)
{
    case Color.Blue:
        label1.BackColor = Color.Red;
        break;
    case Color.Red:
        label1.BackColor = Color.Blue;
        break;
}

You could also keep the code you have in the second snippet but just tell the function you are done by using the return keyword e.g.

if (label1.BackColor == Color.Blue)
{
    // change to red
    return;
}

Or if you want to get really fancy, you could actually refactor the if statement out completely and do it in a one liner - looks pretty ugly though...

label1.BackColor = checkbox1.Checked ? label1.BackColor = Color.Blue ? Color.Red : Color.Blue : label1.BackColor

FYI - if (checkbox1.Checked == true) is a pointless check, just use if (checkbox1.Checked)

Share:
12,162
somethingSomething
Author by

somethingSomething

myreddIT reddiWisdom is knowing that you are nothing, Love is knowing that you are everything and between the two your life moves. First time I was introduced to Linux was in 2007, it was Kubuntu and this person told me about the philosophy and I was told that you are not a real Linux user if you are not programming in Linux. I've been using Linux for everyday use since 2009. I started to use Linux for real in 2012. L'amour, la chaleur et la paix! ´ó ^ĸØ←←{}¬^²³»»»»»»»»»»»»»»»»»»»»»»»»»»»» P.S. Earth is for f * * K sake flat as a pancake, I kid you not The Best Flat Earth Documentary ...... If you want to know more goto ericdubay.com or find Eric Dubay on youtube(https://www.youtube.com/channel/UC0_CSKUIVVFlfocgezQEBDg/videos) Humans are in jail and everthing in our society is made to imprison us, but don't despair help is here and things are changing. We were seen as threats to the real world and illegal because we are 97% ape but what they didn't know is that we are 3% g o d l y watch this and see that this is not a human song, there are beings and higher entities everywhere:Grimes - Genesis. The world we live in is not a world, it's a highly advanced computer, the creators name is 42. There are many secrets hiding in movies. If you don't believe me then,↓↓↓↓ Watch this youtube song: (Grimes - We Appreciate Power) https://www.youtube.com/watch?v=gYG_4vJ4qNA When you listen to music, notice how the singer is talking to someone, it could be you he's talking to but there is also a being you should know about that all songs are referering to:↓↓↓↓↓↓↓ Watch and listen to this song; (Gwen Stefani - What You Waiting For) stupid boy, take a chance you st*** Check this website out, it's awsome: https://debgen.simplylinux.ch/

Updated on June 04, 2022

Comments

  • somethingSomething
    somethingSomething almost 2 years

    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.

  • Catalin
    Catalin about 11 years
    Yes, just add an else if there
  • Smith.Patel
    Smith.Patel about 11 years
    While showing an alternative way can be useful, you are not actually answering the OP's question of why the first case works, but not the second. If you were to answer the question in addition to the alternative way I'd +1 your answer.
  • Smith.Patel
    Smith.Patel about 11 years
    Depends on if the message that the box is not checked is a requirement.
  • James
    James about 11 years
    @JasonDown the colour should alternate if the checkbox is checked, so in the one-liner if the box isn't checked it just keeps back colour the same. Obviously, if the OP needs to throw a message box up then you wouldn't even need that part as the code would only ever be executed when we are in a "checked" state.