Cameron Fairburn Cameron Fairburn - 9 days ago 10
C# Question

Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement?

So I'm trying to make a lock where the background color changes in the different stages of the lock. I'm currently getting the error from the title in the last and second to last brackets - sorry it may be a really noob question I'm new to this.

int intLocked = -1;

if (intLocked == 0)
{
this.BackColor = System.Drawing.Color.Red;
}
{
if (intLocked == 1)
}
{
this.BackColor = System.Drawing.Color.Gold;
}
{
if (intLocked == 2)
}
{
this.BackColor = System.Drawing.Color.Green;
}

Answer

Your if statements are written in the wrong syntax. The correct syntax is:

if (condition) 
{
    // do stuff
}

If you want to check for multiple values for a variable, you could do:

if (myVar == 0)
{

} else if (myVar == 1)
{

} else if (myVar == 2)
{

}

I suppose what you want is this:

if (intLocked == 0)
{
    this.BackColor = System.Drawing.Color.Red;
} else if (intLocked == 1)
{
    this.BackColor = System.Drawing.Color.Gold;
} else if (intLocked == 2)
{
    this.BackColor = System.Drawing.Color.Green;
}

Or, you can use a switch statement:

switch (intLocked)
{
case 0:
    this.BackColor = System.Drawing.Color.Red;
    break;
case 1:
    this.BackColor = System.Drawing.Color.Gold;
    break;
case 2:
    this.BackColor = System.Drawing.Color.Green;
    break;
}

For more info on if statements, visit here.