If you ask what happens to objects referenced by variables in static methods, then these objects become available for garbage collection when they are no longer in scope.
If you are talking about objects referenced by static fields, then they will not be collected in simple words until the links are set to zero.
The following example may illustrate this better:
class Example { private static object field1 = new object(); public static void SomeMethod() { object variable1 = new object();
The object referenced by field1 will be created when the class is loaded and remains root, even if the objects of the Example class are created and destroyed. The only way to collect this object garbage is to call the Deref () method, which will dereference it by setting a reference to null. (In fact, you can unload classes by unloading the application domain, but this is somewhat more advanced, and not that you probably often come across this.)
Conversely, the static SomeMethod () method creates an object and refers to it with variable1. This object is intelligent for garbage collection as soon as it goes beyond the scope (at the end of the method). As a rule, it could be assembled earlier if the rest of the method does not refer to it.
Paul ruane
source share