1

I have the code like as below:

static void Main(string[] args)
{
    List<Dictionary<string, string>> abc = new List<Dictionary<string, string>>();

    Dictionary<string, string> xyz = new Dictionary<string, string>();
    Dictionary<string, string> klm = new Dictionary<string, string>();

    xyz.Add("xyz_1", "4");
    xyz.Add("xyz_2", "5");

    klm.Add("klm_1", "9");
    klm.Add("klm_2", "8");

    abc.Add(xyz);
    xyz.Clear();
    /*after this code xyz clear in my abc list. Why ?*/
    abc.Add(klm);
}

I am creating list of dictionaries. And then I am adding dictionaries to this list. But when added, I am running clear function on my Dictionary, then it is getting deleted from my list as well. Normally my 'abc' list should have xyz, and klm dictionaries with their values. But xyz value count will be 0 after running clear(). How can I prevent this situation?

asingh
  • 56
  • 1
  • 5
Dvlpr
  • 453
  • 3
  • 8
  • 20
  • Because the dictionary is a reference type... meaning that the object you added to the list and the one referenced by `xyz` are the same object. When you `Clear()` the "one" it influences the "other" - 2 references pointing at the same object – Gilad Green Nov 02 '16 at 08:58

1 Answers1

9

I'ts because xyz refrence is added to abc. Use:

abc.Add(new Dictionary<string, string>(xyz));
Noam M
  • 3,156
  • 5
  • 26
  • 41