Search code examples
vb.netdispose

Disposing of Child Classes inside Lists


I have a container class that represents a set of files. There are 10 different types of files, and 24 hourly files per type of file. I've created a child class per file type, and a list of 24 hourly child classes, so a total of 240 classes.

When I am done with the container class, I would like to dispose of it, but do I need to dispose of all the individual class instances? This is my code on the Container class dispose method, but I can't figure out how to call the dispose method on all the child classes. The reason I believe I need this is because I will likely have to add more classes and lists as my project grows. Any help is appreciated!!

     Public Sub Dispose() Implements IDisposable.Dispose
            Dim objType As Type = Me.[GetType]()
            Dim properties As PropertyInfo() = objType.GetProperties()

            For Each [property] As PropertyInfo In properties
                Dim tColl As Type = GetType(ICollection(Of ))
                Dim t As Type = [property].PropertyType
                Dim name As String = [property].Name
                'check for collection
                If t.IsGenericType AndAlso tColl.IsAssignableFrom(t.GetGenericTypeDefinition()) OrElse t.GetInterfaces().Any(Function(x) x.IsGenericType AndAlso x.GetGenericTypeDefinition() = tColl) Then
                    Dim listObject As IEnumerable = DirectCast([property].GetValue(Me, Nothing), IEnumerable)
                    If listObject IsNot Nothing Then
                        Dim enumerable = TryCast(listObject, IEnumerable(Of Object))
                        Dim list = enumerable.ToList()
                        For i = 0 To list.Count - 1
'dispose of child classes, like list.item(i).dispose
                        Next
                    End If
                End If
            Next
            GC.SuppressFinalize(Me)
        End Sub

Solution

  • if you do want to explicitly dispose of them, you can do it in the same method where you created them (once you've finished with them). Doesn't have be be done in the parent object.