whytheq
whytheq

Reputation: 35597

toggling between two states - the elegant way

Simple example of toggling between two states:

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

It works fine but are there alternative ways of coding this toggle? Possibly shorter, more elegant logic.

Upvotes: 2

Views: 1904

Answers (1)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48580

If there are only one statement in if-else clause then we can remove curly braces. So your code will be like

if (this.lblColorChange.BackColor == Color.Red)
    this.lblColorChange.BackColor = Color.Blue;
else
    this.lblColorChange.BackColor = Color.Red;

OR

we can use Ternary Operator

this.lblColorChange.BackColor = 
          this.lblColorChange.BackColor == Color.Red ? Color.Blue : Color.Red;

We can also remove this from our statements if they do not cause any conflict.

lblColorChange.BackColor = 
                lblColorChange.BackColor == Color.Red ? Color.Blue : Color.Red;

Upvotes: 3

Related Questions