0

In my program I found that when asssigning a variable to another, modifying the first one, also modifies the second.

Example:

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Dict_test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void TestButton_Click(object sender, EventArgs e)
        {
            Dictionary<string, int> Dict1 = new Dictionary<string, int>();
            Dict1.Add("one", 1);
            Dict1.Add("two", 2);

            Dictionary<string, int> Dict2 = new Dictionary<string, int>();
            Dict2 = Dict1;

            Dict1.Remove("two");

            MessageBox.Show(Dict2["two"].ToString());

        }
    }
}

Is there a way to make sure that Dict2 doesn't change when changing Dict1.
If possible without const Dict2
I come from a python environement and find this very disturbing
Thanks in advance :)

1 Answers1

3

What you are currently doing:

Dict2 = Dict1;

Is reference copying, so both Dict1 and Dict2 are pointing to the same location. You can create a new copy like:

Dict2 = Dict1.ToDictionary(d=> d.Key, d=> d.Value);

Remember, if your Key and Value are custom objects (based on some class), in that case your second dictionary will have references for the same objects as first dictionary. See How do you do a deep copy of an object in .NET (C# specifically)?

Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436