Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code confusion - why does one work, but not the other?

Note: This already works fine, but I'm trying to understand Why it works this way, but not the other.

I have a WinForm (C#) with dynamically put images, like so: enter image description here

Now if you click the 'Napred' button, these images should be deleted (among other things), for which I originally used:

foreach(Control ctrl in Controls)
    if(ctrl is PictureBox) ctrl.Dispose();

or

for(int i = 0; i < Controls.Count; i++)
    if(Controls[i] is PictureBox) Controls[i].Dispose();

Now if I run this, I get:

enter image description here

But if I just change the for statement to send it backwards, it works?

for(int i = Controls.Count - 1; i >= 0; i--)
    if(Controls[i] is PictureBox) Controls[i].Dispose();

(I'm not going to upload another image, but it deletes all of the elements (I only get the buttons left in the end))

Can someone enlighten me why one works, but not the other?

EDIT: I'm using VS2015 community edition on Windows 10 if it's a debugging error(?)

like image 526
NemanjaT Avatar asked Dec 03 '15 09:12

NemanjaT


1 Answers

You're trying to change the list you're iterating over, which of course will change the indexes of this list so what was at index 1 is now at index 0.

By removing from the end of the array (I.e in your reverse), the previous indexes will always be the same.

Its also important to note as stated in Matthew Watson's comment:

Control.Dispose() is special and will remove the control from a parent container's Controls list.

This isn't default behavour by most Dispose methods so therefore you won't always find this behaviour when using Dispose

like image 116
Sayse Avatar answered Oct 16 '22 06:10

Sayse