Arif Nadeem Arif Nadeem - 3 months ago 8
C# Question

Use for loop with if and else

I have a situation where I have to do some thing like this

for (int i = 0; i < list.size; i++) //Master for loop
{
//I need a control statement here to control list1 i.e. only if statement

if (time == list1.get(someInteger))
{
//do something
}
else
{
//do something else
}
}


But every "if" should be followed by an "else", and I don't seem to understand how to go about it. Ive tried do and while but to no avail. For me it is important to execute both if and else, yet have a control statement for only "if".

Is that possible?

Answer

With your current constraints and description and rational assumptions No.

For me it is important to execute both if and else, yet have a control statement for only "if".

This violates the specification of what a if...else... is. You cannot execute both if and else and keep the if...else... structure. Logically you could drop the else and just have the code in the else inside the loop as other answers have pointed out. However, if you actually do need to keep if and else you need to clarify why so we have a context to answer your question.

If there is some tricky stuff unstated here you might also have a look at switch and use a Goto Case setup. Might be worth saying this probably wouldn't be recommended by many seasoned programmers. Switch statement fallthrough in C#?