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?
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.