Re: newbie garbage collection confusion

Tech-Archive recommends: Speed Up your PC by fixing your registry

From: Jon Skeet [C# MVP] (skeet_at_pobox.com)
Date: 07/29/04


Date: Thu, 29 Jul 2004 22:21:33 +0100

Lionel <Lionel@discussions.microsoft.com> wrote:
> Hello all. I'm learning C# after years of C++ and I'm having some
> trouble getting used to the concept of "garbage collection". I
> understand that an object is created using the "new" keyword and it
> doesn't require manual de-allocation due to the garbage collection
> scheme. But what about scope? In C++ a dynamically allocated object
> is persistant until it is de-allocated. What happens in C#? Is it
> flagged for cleanup when it exits the local code block?

No. An object is eligible for garbage collection when there are no live
references to it - basically when nothing can get to it. It will only
be actually collected when the garbage collector next runs. (There are
some extra concepts too, like finalization and generations - but let's
ignore those for the moment.)

> If so, how do I make an object persistent? If not, when I'm done with
> the object how should I indicate to the framework that it should flag
> that object for garbage collection?

Things generally "just work". Objects will naturally end up becoming
eligible for garbage collection at the right time, usually.

-- 
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too