Garbage collection of C# Lists

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By emild

Suppose I have a List of objects _activeObjs, some of which I want to remove when they are no longer needed. I do so in each process loop. I could achieve this either by

List<MyObj> stillActiveObjs= new();
	foreach (var obj in _activeObjs)
	{
		var stillActive = obj.Update(delta);
		if (stillActive)
		{
			stillActiveObjs.Add(obj);
		}
	}

	_activeObjs = stillActiveObjs;

or by

List<MyObj> stillActiveObjs = new();
	foreach (var obj in _activeObjs)
	{
		var stillActive = obj.Update(delta);
		if (stillActive)
		{
			stillActiveObjs.Add(obj);
		}
	}

	_activeObjs.Clear();
	_activeObjs.AddRange(stillActiveObjs);

Now, I see why the first one might be a problem. There could still be some references to the old _activeObjs and thus it could become a problem. However, by profiling and debugging, I found that also the second option results in an ever increasing number of Lists on the heap. Why is the stillActiveObjs List not garbage collected properly? After all it is only a local variable.