I'm using dictionaries in C#, and I've spent a couple of hours figuring out why my program doesn't work, and the reason is that when I manipulate a copy of a dictionary I made, then these manipulations also affect the original dictionary for some reason.
I've boiled my problem down to the following example:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<int, List<int>> D = new Dictionary<int, List<int>>();
List<int> L1 = new List<int>(){ 1, 2, 3 };
List<int> L2 = new List<int>() { 4, 5, 6 };
D.Add(1,L1);
D.Add(2,L2);
Dictionary<int, List<int>> Dcopy = new Dictionary<int, List<int>>(D);
Dcopy[1].Add(4);
}
}
In this code, when I add an element to the list corresponding to key 1 in the copy, this element also appears in the original dictionary.
When I search online, it seem to have something to do with "reference types", and the recommended fix always seem to involve a code similar to
Dictionary<int, List<int>> Dcopy = new Dictionary<int, List<int>>(D);
which I did include in my program, but for some reason, this does not work.
Any suggestions as to why it doesn't work in my case, and any advice on what to do instead?
Best regards.