Is VB.Net object out of scope?

This expands on the question asked last year.

Public Class RandomClassManager
    Private mCol As Collection

    Private Sub Foo()
        Dim ob as New MyRandomClass
        Add(ob)
    End Sub

    Public Sub Add(ByRef mc As MyRandomClass)
        mCol.Add(mc)
    End Sub
End Class

      

Once it Foo

comes out, can I trust mCol

to keep MyRandomClass

objects in it ? Or am I being threatened by the garbage collector deleting these objects?

+3


source to share


1 answer


Yes, you can trust that the newly created object MyRandomClass

is still in mCol

. Once the list has a reference to an object, the garbage collector will not destroy it. Or at least not until something else is referencing mCol

, that is ... The garbage collector will not destroy any object that strongly references any other object.



For what it's worth, if you want to allow the garbage collector to destroy objects even though they're still in the list, you can wrap them in WeakReference

.

+4


source







All Articles