Reputation: 29
Not sure what I am doing wrong here. I am new to C# and am trying to convert VB.Net code from an online tutorial. I can't get this For loop to iterate:
if (Screens.Count > 0)
{
for (int i = Screens.Count - 1; i == 0; --i)
{
if (Screens[i].GrabFocus==true)
{
Screens[i].Focused = true;
DebugScreen.FocusScreen = "Focused Screen: " + Screens[i].Name;
break;
}
}
}
There are 2 screens in the list. The second screen (Screens[1]) has GrabFocus set to true. During debugging, execution jumps from line 3 (for ...) right to the last closing brace. The nested "If" statement never executes. Also, I think the break statement is wrong because I am actually trying to end the "For" loop.
Upvotes: 0
Views: 110
Reputation: 53958
You haven't written correctly your for
loop. You should replace it with the following:
for (int i = Screens.Count - 1; i >=0; --i)
You start from the value Screens.Count - 1
and you decrease by 1 the i
in each step, until i
becomes equal to zero. Then you stop.
Generally speaking, the correct syntax is the following:
for (initializer; condition; iterator)
body
For more information about this, please have a look here.
What's the problem in your case?
The second bullet. The condition, i==0
is false by the begin. Hence the loop will not be executed at all.
Upvotes: 4
Reputation: 88
Your for loop
is not correct. Here's is the code
if (Screens.Count > 0)
{
for (int i = Screens.Count - 1; i >= 0; --i)
{
if (Screens[i].GrabFocus==true)
{
Screens[i].Focused = true;
DebugScreen.FocusScreen = "Focused Screen: " + Screens[i].Name;
break;
}
}
}
Upvotes: -1
Reputation: 15923
i == 0
should be replaced with i >= 0
for (int i = Screens.Count - 1; i >=0; --i)
Upvotes: 0
Reputation: 300559
i == 0
should be i >= 0
i.e.
for (int i = Screens.Count - 1; i >= 0; --i)
Upvotes: 0