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?
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With