I’ve been doing some reading on garbage collection in .NET and I was hoping for some clarification. So, as I understand it if I declare a public shared class variable, the GC will never get rid of it. Is this correct?
Also, what then of private variables? Take the following example:
public class myClass
private shared myString As String
public sub ChangeString(newString As String)
myString = newString
end sub
end class
Would the shared variable now get GCed if there were no instances of the class? And what if I alter ChangeString to be a shared sub?
Almost. The GC will not clean up the string that your Shared variable references.
If, however, you call
ChangeStringwith a new string, the string that was pointed to bymyStringwill no longer be rooted by this reference, and may be eligible for GC. However, the new string (referenced bynewString) will now become rooted by themyStringvariable, preventing it from garbage collection.No. The shared variable roots the object, since it’s owned by the “type” of the class, not any instances.
This will have no effect at all.