views:

84

answers:

3

I have the following nested dictionaries:

  1. Dictionary<int, Dictionary<string, object>> x;
  2. Dictionary<int, SortedDictionary<long, Dictionary<string, object>>> y;

If I do x.Clear() and y.Clear() will all the nested objects clear and all the memory will be reused on the next garbage collection?

Or do I need to iterate on all the items and clear them manually?

+4  A: 

If none of your objects are reachable from other parts of your code, they will all be garbage collected.

If this will be done on the next garbage collection, depends on the generation that they belong to.

This article from Jeffrey Richter explains a lot.

GvS
Of course determining this could be the hard part, but in essence this is how GC works.
Preet Sangha
A: 

It's the same for everything: the GC starts from its roots (variables on the stack and various other odd cases) and walks the tree of reachable objects by following references. Any objects not found by that process will be eligible for collection.

So as long as your removed sub-dictionaries are not reachable some other way, they will be collected.

Daniel Earwicker
A: 

Maybe yes.

If you have references to items in the dictionary, regardless of the type of the value parameter, than those objects won't be collected.

But if there are no references, then they will be collected (at some point).

Krisc