Home > Blockchain >  A followup if statment
A followup if statment

Time:11-02

My question is a bit hard to describe so I have written a hypothecical code (nonfuctioning) down below and I wonder if there is a similar alternative in C#:

if(Red == true)
{ 
i -= 3;
}
else if(Yellow == true)
{ 
i -= 2
}
then
{
 list.Clear();
}
else{}

A "then" function of sorts that both if statements follow if one where to execute. The use of this would simply be so that I do not need to do in this case a list.Clear(); in every if statment.

CodePudding user response:

No there is no syntax construct like your then but you can create a method that clear the list and accept and returns the value to decrement

private int ClearAndDecrementBy(int decrement)
{
    list.Clear();
    return decrement;
}

and call it as

if(Red)
{ 
   i -= ClearAndDecrementBy(3);
}
else if(Yellow)
{ 
   i -= ClearAndDecrementBy(2);
}
else
{

}

Not really sure that there is any advantage though. The list should be declared at the global class level and this is never a good practice if it is needed only to make it work in this way. So, adding the call to list.Clear inside the if blocks seems more clear and it won't do any harm

CodePudding user response:

Try this:

if(Red == true)
{ 
  i -= 3;
}
else if(Yellow == true)
{ 
  i -= 2
}
else
{
}
if(Red == True || Yellow == true) //You can add more like: Blue == true
{
    list.Clear();
}

CodePudding user response:

You could get rid of the "then" statement from your pseudo code and add the following line to the end of everything.

if (Red || Yellow)
{
   list.Clear();
}

CodePudding user response:

try this

        if (Red || Yellow)
        {
            i = Red ? -3 : -2;
            list.Clear();
        }
        else { }
  • Related