tags:

views:

38

answers:

4

for example in this code:

void ButtonCreator()
{
    Button elboton = new Button();
}

what happens with elboton after I call this method?

+5  A: 

If they're not referenced by some other object (e.g. a container), then they become unreachable and are eligible for collection by the garbage collector. This is the same as creating any other object.

Note that the System.Windows.Forms.Control class (and its subclasses like Button) all implement the IDisposable interface, so the easiest way to make sure any unmanaged resources associated with the Button are released is to use a using block, like so:

using(Button elboton = new Button()) {
    // Do whatever you need to do
}
// elboton is now disposed

However, any managed resources associated with the object won't be reclaimed until the GC runs, regardless of whether or not you use a using block.

Daniel Pryden
@D.P.: is the garbage collecting done automatically? or how do "summon" it? =P
Luiscencio
Yeah, the GC runs sporadically when the runtime "feels" it makes sense to do so.
Lucero
so, can GC be called programmatically? or just "when the runtime feels it makes sense to do so"?
Luiscencio
It *can* be called programmatically, but that's usually not a good idea - let the runtime handle this, it knows more about the computer and the memory situation than your application. (To trigger a collection, have a look at the `GC` static class.)
Lucero
A: 

All references to it are destroyed and in turn the garbage collector will eventually gobble it up. If you assign that button to exist in some other context (add a reference to it that last beyond the scope of this method) it will stay.

NickLarsen
A: 

There will be no reference on that instance and it will be cleaned up by the GC after a while...

Rico
A: 

In your example elboton will be collected by the GC (garbage collector) when the next GC iteration starts. This is because it is not referenced just after ButtonCreator() finishes.

Igor Korkhov