I have the following class with the following methods:
public class Foo
{
public string A {get;set;}
public static Foo New(string a)
{
Foo newFoo = new Foo();
newFoo.A = a;
return newFoo;
}
}
public class Bar
{
public void SomeMethod()
{
...
Foo anotherFoo = Foo.New("a");
....
}
}
If the Bar class creates Foo during a process using the above code, will Foo ever go out scope and get garbage collected or will Foo (because it is using a static method) continue to have a reference to variable newFoo and therefore anotherFoo will never go out of scope?
The presence of static methods doesn’t impact an object’s eligibility for GC, only references to that object do. In your case
anotherFoowill be the only reference. The referencenewFoogoes out of scope when the method returns, popping off the stack.Local variables inside static methods are not themselves “static”, when the method returns, those locals will be popped from the execution stack the same as non static methods.
The underlying object behind
anotherFoowill become eligible for GC whenSomeMethodreturns (well, the compiler is more aggressive and can make it GC-able whenanotherFoois no longer used in the code).