Let’s say we have the following code in a class:
//class code
TextBox t = new TextBox();
ListBox l = new ListBox();
We have then two possible situations:
In the first, we declare qem1 as a class variable(or attribute, as they call it in the Java World):
//class variable
QuickEntryMediator qem1 = new QuickEntryMediator(t,l);
In the second, we declare it inside a method:
//method variable
QuickEntryMediator qem2 = new QuickEntryMediator(t,l);
So, I’d say qem1 would never be Garbage Collected before the class goes out of scope while in the qem2 might be Garbage Collected at any time after the method in which it resides dies. Is this true?
I am looking for answers for both C#(.net) and Java, as am I am not sure both GC’s work in the same fashion!
Thanks
Note that in C# (and I believe in Java as well) an object is eligible for collection the moment is no longer strongly referenced (directly or indirectly), and this could happen before the reference variable goes ‘out of scope’, as long as the reference is no longer used. Objects can be collected while still in scope, as long as the runtime can determine that they are no longer necessary (ie., the program is done with any references to the object).
So
qem2could be eligible for collection long before the method it’s defined in ‘dies’ *by which I think you mean returns), but the depends entirely on howqem2is used.With the following simple C# code, the mutex created at the start of
Main()might be garbage collected at any point after its creation – it might not live until the end of the scope ofMain()because nothing ever references it after it’s created.See the following for more information.
Note that at least in .NET, running under a debugger will keep objects alive until the end of scope, so if you’re going to test this out make sure you do it outside of a debugging situation.