Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the List Clear() method destroy children [C#.NET]?

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?

like image 265
Jon Smock Avatar asked Nov 10 '08 18:11

Jon Smock


2 Answers

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).

like image 57
Godeke Avatar answered Sep 23 '22 15:09

Godeke


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.

like image 35
chakrit Avatar answered Sep 23 '22 15:09

chakrit