Will reference instance parameters passed to static methods be garbage collected?
I know that static objects in a .Net driven world are loaded into the Loader Heap, which is never going to be garbage collected.
What happens to the instance reference parameters passed to static methods. Do they get garbage collected when the static function is completely executed, or will they live forever as these reference instance variables are once passed to the static method?
I'm really confused this evening; Please guide me.
Thanks and greetings
123Developer.
a source to share
Just because you are passing a reference to a static method does not in any way mean that the object will be rooted in any way, so it alone is not enough to prevent collection.
Whether it can be collected during a method call or only after its completion depends on what the method does with the argument and whether the object is used outside of the method call.
For example, consider this hypothetical code:
public static class Program()
{
public static void Main()
{
SomeObject o = new SomeObject();
OtherMethod(o);
}
private static void OtherMethod(SomeObject x)
{
// lots of code here, but none that uses x
}
}
in this case o can be built at call time OtherMethod
if you compile and run the release build. For release versions, variables and parameters that are no longer used, that is, there is no code that uses it, are considered dead and are therefore no longer counted when checking for live object references.
In the Debug build, all variables and parameters are artificially maintained until the methods return, so you can breakpoint and check the variable even though there is no code that uses it.
So, if you want to run the above code from a debug build, then the object will be persisted until Main returns.
a source to share
Once a static method is executed on a variable, it no longer references it (if you assign it to a static variable, then another). This does not mean that it will collect garbage immediately. Unless you specifically specify that the GC will run when it does, it will be based on when the runtime thinks it needs to free memory. In truth, it may not always be during the lifetime of the application (resources will be freed up when the application ends). However, this is unlikely, although technically possible.
a source to share