C# memory / allocation cleanup

Posted by Number8 on Stack Overflow See other posts from Stack Overflow or by Number8
Published on 2012-10-18T16:51:29Z Indexed on 2012/10/18 17:01 UTC
Read the original article Hit count: 204

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about memory-management