Steve London
Steve London

Reputation: 31

VB.Net object out-of-scope?

This expands on a 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 Foo exits, can I trust mCol to still have MyRandomClass objects in it? Or am I at risk of the Garbage Collector removing those objects?

Upvotes: 3

Views: 63

Answers (1)

Steven Doggart
Steven Doggart

Reputation: 43743

Yes, you can trust that the newly created MyRandomClass object is still in mCol. Once the list has a strong-reference to the object, the garbage collector will not destroy it. Or at least not as long as something still references mCol, that is... The garbage collector will not destroy any object that is strongly-referenced by any other object.

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

Upvotes: 4

Related Questions