C# memory / allocation cleanup
- by Number8
Some near-code to try to illustrate the question, when are objects marked as available to be garbage-collected --
class ToyBox
{
public List<Toy> Toys = new List<Toy>();
}
class Factory
{
public ToyBox GetToys()
{
ToyBox tb = new ToyBox();
tb.Toys.Add(new Toy());
tb.Toys.Add(new Toy());
return tb;
}
}
main()
{
ToyBox tb = Factory.GetToys();
// After tb is used, does all the memory get cleaned up when tb goes out of scope?
}
Factory.GetToys() allocates memory. When is that memory cleaned up? I assume that when Factoy.GetToys() returns the ToyBox object, the only reference to the ToyBox object is the one in main(), so when that reference goes out of scope, the Toy objects and the ToyBox object are marked for garbage collection.
Is that right? Thanks for any insights...