0

Let's say I have an update loop from a game and every loop I output a new list from a class function and assign it to 'myList'. What happens to the list from previous update functions? Do I have to worry about it?

//someClass
List<T> GetList()
{
   List<T> l = new List<T>(); // I create a new list here
   //populate the list.....
   return l; 
}

------------------
void Update()
{
  //game update loop
  List<T> myList = someClass.GetList(); 
  //what happens to the previous instance of list created?
}
Uyet123
  • 47
  • 4

1 Answers1

1

Lists are reference types. When you do something like this:

List<T> l = new List<T>();

new List<T>() creates a list object. l holds a reference to that object. When you create another list object and assign it to l:

l = new List<T>();

These things happen:

  • The original object is not destroyed
  • a new list object is created
  • l now stores a reference to the new object

Some other variables in your code might still be referring to the original list object. If not, then the following happens.

The original list object is now eligible for garbage collection. the garbage collector will, at some undetermined point in time, free up that chunk of memory.

Note:

After rereading your code. I found that your code does not really do what you describe. You only ever created one instance of the list. This means that in your code, the instance will be referenced by l and hence will not be garbage collected.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Don't I create multiple instance of the list from the Update function? Since I call GetList() every loop a new list is created. – Uyet123 Aug 04 '17 at 12:13