If I do the following:
public class Test
{
public static void Main()
{
List<Person> persons = new List<Person> { new Person() };
persons[0].Sneezing += new EventHandler(Person_Sneezing);
persons = null;
}
public static void Person_Sneezing(object sender, EventArgs e)
{
(sender as Person).CoverFace();
}
}
Does the person that was in person[0] still exists in memory because it's Sneezing delegate has a reference to the Person_Sneezing method or does it get collected by the GC?
In the common language runtime (CLR), the garbage collector (GC) serves as an automatic memory manager. The garbage collector manages the allocation and release of memory for an application. For developers working with managed code, this means that you don't have to write code to perform memory management tasks.
Garbage collection ensures that a program does not exceed its memory quota or reach a point that it can no longer function. It also frees up developers from having to manually manage a program's memory, which, in turn, reduces the potential for memory-related bugs.
Does the garbage collector sweep stack memory? No. The garbage collector does only manage heap memory. All values on the stack are expected to be needed again when the program returns to that stack frame, so they must not be collected.
An object is eligible to be garbage collected if its reference variable is lost from the program during execution. Sometimes they are also called unreachable objects.
This will be collected by the GC. To be kept in memory an object must be referenced directly or indirectly by ...
This is not true for the object at persons[0]. So it will be collected.
That is of course assuming the constructor for Person() doesn't do anything funny like add itself to ThreadLocalStorage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With