Saturday, 15 September 2012

Will the garbage collector collect the objects created by this C# code? -



Will the garbage collector collect the objects created by this C# code? -

i have next code:

public abstract class state { public abstract void handlestate(); } public class statea : state { public override void handlestate() { // stuff here .... // returns new state object, , there multiple, stateb, statec etc. state newstate = getnewstate(); newstate.handlestate(); } }

assuming state objects maintain getting returned ad-infinitum, garbage collector ever able collect objects generated code?

well, depends on getnewstate returns. if creating stack overflow (as frédéric hamidi pointed out) creating new instances of statea, you'll stackoverflowexception (most before gc seek run).

however, provided getnewstate() returns instance of else doesn't create objects in turn creating new state objects recursively, garbage collected @ point after no longer referenced (garbage collection non deterministic , clean unused memory when gets around it).

example of implementation wouldn't cause stack overflow:

public class stateb : state { public override void handlestate() { // stuff here - doesn't maintain creating new state objects. .... } }

as eugene podskal pointed out, created classes create reference cause them not garbage collected. such as:

public class statec : state { private static list<statec> _mystates = new list<statec>(); public statec() { //unless items removed @ point _mystates, // won't garbage collected. _mystates.add(this); } public override void handlestate() { // stuff here } }

c#

No comments:

Post a Comment