Leo Christensson
Leo Christensson

Reputation: 27

A followup if statement

My question is a bit hard to describe so I have written a hypothetical code (nonfunctioning) 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 statement.

Upvotes: 0

Views: 94

Answers (4)

Serge
Serge

Reputation: 43900

Try this:

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

Upvotes: 0

Steve
Steve

Reputation: 216302

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

Upvotes: 1

John C.
John C.

Reputation: 114

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

Upvotes: 0

user17289254
user17289254

Reputation:

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

Upvotes: 0

Related Questions