C# loops not looping an if statement

I have an if statement within a loop, using Debug.Write() I've determined that for the first iteration of the loop everything works as expected, but on subsequent iterations the if block is ignored, but everything else within the loop still executes. I've tried a few variations but so far none of them have worked.

Originally I had:

Private int Loop()
    int a = 50000;
    int n = 0;
    for (int n = 0; n < arrayListFromElsewhere.Count(); n++)
        if ((int)arrayListFromElsewhere[n] < a)
            Debug.WriteLine("if loop: " + n);
            a = n;
        Debug.WriteLine("N: " + n);

Which would print:

if loop: 0
N: 0
N: 1
N: 2

I've verified that the ArrayList only ever contains integers, replaced the for with a while and tried moving the if into a separate function which is called inside the for/while but nothing has worked so far. So what super obvious thing have I overlooked?


After the first iteration of the loop, you've set a to n. From then on, you'll only go into the if statement if the value in the ArrayList is negative. Are any of the values negative? (A short but complete example of the failure would really have helped, by the way - as well as some explanation of what you're trying to do.)

(As an aside, why are you still using non-generic collections? 2004 is calling - it wants its code back!)

the first time though the loop a = n while n is zero so when the if is evaluated the second time n =1 a = 0 arrayListFromElsewhere[n] = something > 0

On your first iteration a becomes 0 (the value of n on your first run).

After that the if statement if ((int)arrayListFromElsewhere[n] < a) is always false.

yes, the if block will be ignored based on the condition as you specified. Since in the first if block, you have set a = n. in that case a will be 0. So, subsequent if block will be false and will not be executed.

If you only have positive numbers in the array, after the first iteration a will be 0 (first n in the if is 0) and it will not enter the if any more.

Also, you have n declared twice.

Need Your Help

Php non-blocking soap client

php soap nonblocking

I'm using a lot of webservices a huge php application.

Grails Database Mapping

mysql grails mapping

my problem is my database mapping and i don't get it working.