Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will the garbage collector free this List when my method finishes running

Lets say I have something like:

public class Item
{
    public string Code;
    public List<string> Codes = new List<string>();
}

private void SomeMethod()
{
    List<Item> Items = new List<Item>();
    for (int i = 0; i < 10; i++)
    {
        Item NewItem = new Item();
        NewItem.Code = "Something " + i.ToString();
        NewItem.Codes.Add("Something " + i.ToString());
        Items.Add(Item);
    }

    //Do something with Items
}

I am instantiating Item and not free'ing it because I need to have access to it in the list later on (rough example).

What I am wondering is when SomeMethod() has finished executing, will Items (and the contents of it - including the List<>) be de-referenced and allow the garbage collector to clean up the memory as and when it runs? Basically, will this section of code cause any memory leaks or should everything be de-referenced when SomeMethod() has finished processing.

My understanding is that when nothing holds a reference to an object it will be garbage collected so in my mind this code should be Ok but I just wanted to make sure I understand correctly.

EDIT:

If I was to add one of the objects Items is holding into another list that would still be in scope (a global list for example). What would happen?

like image 472
webnoob Avatar asked Dec 13 '12 15:12

webnoob


1 Answers

Once your variable Items goes out of scope, the garbage collector will indeed dispose of it (and its contents, as your code is written) at its leisure.

like image 142
tomfanning Avatar answered Nov 15 '22 12:11

tomfanning