Flavio Caetano Flavio Caetano - 1 year ago 73
C# Question

"Dictionary nest" in C#?

Im beginner in C# and I´m trying to do the following:

I created a Dictionary:

_innerProducts = new Dictionary<string, string>();

then another dictionary to store the first one on it:
_KitProducts = new Dictionary<string, Dictionary<string, string>>();

The first one (_
) contains about 15 products atributes that I collected from and .xml file, and the TKey its the product code.

after collect all the atributes I call:

_KitProducts.Add(_innerProducts["cProd"], _innerProducts);

When I watch this via debug, its works fine, as I can see:

Before Clear

The problem is that I cannot add another group of atributes using the same TKey as the first
"cProd", so inside the foreach I put one
at the end.

The problem is when I Clear it, it clear not only the current _innerProducts, it clear the TValue of the _KitProducts too:

After Clear

Im not sure if this is because of those "by reference" and not "by value" lecture that I read (remember I´m at very beginning), so what should I do in this case?

It will be a lot of those cases, I know that I will need to store it (but I still didnt learn Entity Framework, working on it), while that, Im just storing in the Dictionary to learning purposes.

Thanks and sorry for the english, isnt my main language.

Answer Source

After adding the value to the outer dictionary, both _innerProducts and the value of the outer dictionary entry refer to the same object:

             | your inner dictionary |
                ^          ^
                |          |
      _innerProducts      value in the outer dictionary entry

When executing _innerProducts.Clear(), you empty that dictionary with the following result:

             |    empty dictionary   |
                ^          ^
                |          |
      _innerProducts      value in the outer dictionary entry

Thus, instead of emptying the existing instance, create a new instance, i.e., replace

_innerProducts.Clear();     // "a.DoSomething()" operates on the object referenced by a


_innerProducts = new Dictionary<string, string>();    // "a = ..." defines which object a refers to

That results in the following situation:

   +-----------------------+    +-----------------------+
   |   a new, empty dict.  |    | your inner dictionary |
   +-----------------------+    +-----------------------+
                         ^          ^
                         |          |
               _innerProducts      value in the outer dictionary entry

That way, you don't modify the existing inner dictionary, but instead let the variable _innerProducts point to a new one.

Even simpler and better, if possible: Move the declaration of _innerProducts inside the loop that you use to fill _KitProducts. That will ensure that each loop iteration gets its own instance of the inner dictionary.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download