1

I was wondering how to clean up a list holding objects containing another list.

Like so :

List<Foo> FooCollection = new List<Foo>();

Foo foo1 = new Foo(new List<Bar>());
Foo foo2 = new Foo(new List<Bar>());

FooCollection.Add(foo1);
FooCollection.Add(foo2);

Is this enough ?

FooCollection = null;
Ron
  • 85
  • 5

2 Answers2

0

I wouldn't recommend to set the FooCollection = null, because using List methods, like FooCollection.Add() will throw an exception.

Instead you should use .Clear(); or new List<Foo>();

Based on this benchmark the fastest way is:

FooCollection = new List<Foo>();

If you are sure, that you don't need the FooCollection again, you can use FooColleciton = null. If you want to take care, that the GC give the memory free you can call GC.Collect();

GC Collect Reference

Here you can find some hints, when it is okay to force the garbage collector:

When is it acceptable to call GC.Collect?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sean Stayns
  • 4,082
  • 5
  • 25
  • 35
-1

It depends if you want to use FooCollection later in code.

// reuse the same object
FooCollection.Clear();
// start of with new collection
FooCollection = new List<Foo>();


FooCollection = null;
Józef Podlecki
  • 10,453
  • 5
  • 24
  • 50
  • I don't want to use the list again. Only cleaning it up, so there are no memory leaks. – Ron May 16 '20 at 13:55
  • Where is `FooCollection` used ? inside a function ? When it exits GC eventually cleans stuff up. You are not playing with unmanaged resources are you ? – Józef Podlecki May 16 '20 at 13:57
  • There are no unmanged resources involved. FooCollection is a property of another object, which has a Clear() method. There a set FooCollection = null. – Ron May 16 '20 at 14:04
  • @Ron if you want to give memory free, of course, you can set FooCollection = null; and then you can call GC.Collect(); (See my answer.) – Sean Stayns May 16 '20 at 14:11