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 different.

I have a WinForm (C #) with dynamically allocated images, for example: enter image description here

Now, if you click the "Invalid" 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 modified the for statement to send it back, does it work ?

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

(I will not upload another image, but it removes all the elements (I get only the buttons on the left at the end))

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

EDIT: I am using the VS2015 community version for Windows 10 if it is a debugging error (?)

+7
c # for-loop winforms picturebox
source share
1 answer

You are trying to change the list that you are repeating, which of course will change the indices of that list, so that index 1 is now at index 0.

Removing from the end of the array (Ie in reverse order), the previous indexes will always be the same.

It is also important to note, as indicated in a comment by Matthew Watson:

Control.Dispose () is special and will remove the control from the list of control elements of the container.

This is not the default behavior by most Dispose methods, so you will not always find this behavior when using Dispose

+12
source share

All Articles