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

12,234

Solution 1

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

Solution 2

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.

Solution 3

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.

Share:
12,234

Related videos on Youtube

marie
Author by

marie

Made with real slurm ☃

Updated on April 18, 2022

Comments

  • marie
    marie about 2 years

    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?