Are static members collected by GC when they are no longer needed?

6

In a class that has a static variable, it exists throughout the application. Is the linked object collected at some point?

Example:

public class Exemplo {
    private static List<int> lista = new List<int>();
}
    
asked by anonymous 10.05.2017 / 16:16

1 answer

10

The variable will never be collected, it stays in a static area and as you said, the application lasts. Then any object referenced by it will stay alive all the time. The static object is one of the search roots of the GC, so it will take a reference and keep the object alive.

But obviously there is such a thing as not having to reference that variable. At some point the application can change the reference to another reference and then if the previously referenced object has no other references it will be collected.

Of course, if you override this variable, you will no longer have that reference.

If a reference to the object still exists, you can sign it for this static field again. If you no longer have references to it, you can not use the object again. The resurrection can only occur during the ending of it, which should be avoided. But this is another matter.

Actually, if the variable has the attribute ThreadStatic The variable itself can be collected after the end of the thread .

public class Exemplo {
    private static List<int> lista = new List<int>();
    public static TrocaLista() {
        lista = new List<int>(); //o objeto anterior ficará sem referência
    }
}

I've placed it on GitHub for future reference.

    
10.05.2017 / 16:28