views:

1877

answers:

3

If I create a recursive list of of lists:

class myList
{
  List<myList> childLists;
  List<string> things;

  //...
}

List<myList> tempList = new List<myList>();

And then later call tempList.Clear(), will it destroy all the childLists in memory, or should I create a recursive method to clear all the childLists first?

+9  A: 

If no other references exist to the child lists, they will be garbage collected as normal. The trick is to watch for any dangling references to the child items (databinding especially tends to go unnoticed once done).

Godeke
+1  A: 

You do not need to clear the sub-lists.

The only thing you would have to do is if the objects in your list implements IDisposable, then you should iterate through the objects and call the .Dispose() method before clearing the list.

Lasse V. Karlsen
only do this if you're sure there are no other references to the items in the list, otherwise, other code may attempt to use the Disposed objects
Blair Conrad
+2  A: 

You seem to have come from a C++ background.

A read on .NET's Garbage Collection should clear a lot of things up for you.

In your case, you do not need to "destroy" all the child lists. In fact, you can't even destroy or dispose a generic List object yourself in a normal good-practice .NET way. If you no longer wish to use it, then just remove all references to it. And the actual destruction of the object will be done by the garbage collector (aka GC) when it sees appropriate.

The GC is also very smart, it'll detect circular-references and a->b->c->d object trees and most things you could come up it and clean the whole object graph up properly. So you do not need to create that recursive cleaning routine.

But do note that the GC's behavior is undeterministic, i.e. you won't know when the actual "cleanup" will happen so if your list contains some important resources that should be freed immediately i.e. File handles, database connections, then you should explicitly "Dispose" of it, as @lassevk recommended.

chakrit