Looping through controls to dispose them.

artix

Member
Joined
Oct 5, 2007
Messages
16
Location
Sweden
Programming Experience
1-3
Got a question about looping though controls and disposing them.
In the first example the application skips roughly 1/3 of the JustAClass'es.. while in the second example all of them are disposed.
Any ideas of why?

VB.NET:
For Each c As Control In Me.Controls
  If TypeOf c Is JustAClass Then
    c.Dispose()
  End If
Next



VB.NET:
Dim JustAClassDelete As New List(Of JustAClass )

For Each c As Control In Me.Controls
  If TypeOf c Is JustAClass Then
    JustAClassDelete.Add(c)
  End If
Next

For i = 0 To JustAClassDelete.Count - 1
  JustAClassDelete.Item(i).Dispose()
Next
 
It is due to the enumeration operation that occurs during a 'For Each' Loop a standard 'For Next' loop should solve the problem


VB.NET:
For I as Integer = Me.Controls.Count - 1 to 0 Step - 1
If Me.Controls(i).GetType() Is GetType(JustAClass) Then
Me.Controls(i).Dispose
End If
Next
 
No, you have to do For-Next from top stepping -1 like vis781 said. This because disposing a control also removes it from the collection you are iterating and the collection will truncate in the process, as a consequence when the Each iterator moves to next index it will keep skipping controls. What surprise me is that doing it doesn't throw a InvalidOperationException with the message:
Collection was modified; enumeration operation may not execute.
This is what you usually get when doing that.
 
Back
Top