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?
So, as I understand it if I declare a public shared class variable, the GC will never get rid of it. Is this correct?
Almost. The GC will not clean up the string that your Shared variable references.
If, however, you call ChangeString
with a new string, the string that was pointed to by myString
will no longer be rooted by this reference, and may be eligible for GC. However, the new string (referenced by newString
) will now become rooted by the myString
variable, preventing it from garbage collection.
Would the shared variable now get GCed if there were no instances of the class?
No. The shared variable roots the object, since it's owned by the "type" of the class, not any instances.
And what if I alter ChangeString to be a shared sub?
This will have no effect at all.
The shared variable lives in the class itself, so you don't need an instance of the class for the variable to survive, so your string would not be garbage collected.
It doesn't matter if a variable is private, it still won't be garbage collected. It doesn't matter if you use a sharded method or an instance method to set the variable.
Note: The garbage collector never collects variables, it only collects objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With