tags:

views:

179

answers:

3

I am implementing IDisposable for a class and while disposing there is a internal list of disposable objects. Should I be disposing those object by looping through them.

public Class MyDisposable 
     Implements IDisposable 
     private _disposbaleObjects as new List(of OtherDisposables)

     Public Overloads Sub Dispose() Implements System.IDisposable.Dispose
         Dispose(True)
         GC.SuppressFinalize(Me)
    End Sub

    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                  ? Should I dispose the the list like this ?
                  For Each obj In _disposbaleObjects
                      obj.dispose()
                  Next 
            End If               
        End If
        Me.disposedValue = True
    End Sub

End Class
+3  A: 

Yes, iterate through the list and dispose each item.

Also you can write an extension method:

public static void Dispose(this IEnumerable<IDisposable> collection)
{
    foreach(IDisposable item in collection)
        if (item != null)
            item.Dispose();
}

and call it for your list

_disposbaleObjects.Dispose()
abatishchev
Does VB.Net have extension methods?
Moron
@Moron: Yes it does http://msdn.microsoft.com/en-us/library/bb384936.aspx
abatishchev
+1 then..... :)
Moron
+1 Or alternatively inherit from `List` to define an object that does it for you? http://willsmentaldebris.blogspot.com/2007/08/disposable-container-class.html
MarkJ
+1  A: 

Yes, you need to dispose each of these objects explicitly, exactly the way you're doing it now.

Thomas Levesque
+1  A: 

Who creates the objects inside the list? i.e. who is responsible for their life-cycle? If MyDisposable creates them, then it is its responsibility to dispose of them. If someone else creates them, disposing of them can leave them with a reference to a useless object.

HTH,
Kent

Kent Boogaart
MyDisposable creates the list of objects.
Joker