Rami
Rami

Reputation: 7290

Clear a dictionary of dictionaries

I have a private field in a class which is a dictionary of dictionaries.

private readonly Dictionary<string, Dictionary<int, int>> 
myDict = new Dictionary<string, Dictionary<int, int>>();

What's the best practice regarding clearing myDict? Do I have to loop on all the values and call Clear on each or is it enough if I just called Clear on myDict??
I'm looking for the best performance too.

Upvotes: 4

Views: 945

Answers (3)

Patrick Hofman
Patrick Hofman

Reputation: 156948

If you call Clear(), it will clear the master dictionary. If there are no references any more to the inner dictionaries, the garbage collector will clean them up, so there is no need to call Clear() on them. If they are still being referenced, you have to unreference those first on you might end up with an invalid state.

Upvotes: 7

A Person
A Person

Reputation: 1112

If you keep (pointer-)copies of the 2nd level dictionaries somewhere it is saver to clear all of them. If you only access them directly trough the "mother" dictionary or temporary variables inside of a method they are collected by the garbage collector sooner or later so you don't have to Clear them seperately.

Upvotes: 0

Mukul Keshari
Mukul Keshari

Reputation: 505

Just called Clear on myList this is the best way.

In you code I can see myList is readonly, check if it can be cleared or not.

Upvotes: 0

Related Questions