Dictionary assignment in C#

Dictionary

class, representing a collection of keys and values.
,tvalue>

Dictionary

generic classes provide a mapping of a set of keys to a set of values. Each addition to the dictionary contains a value and its associated key. It is very fast to retrieve values using its keys.
,tvalue>


Before using Dictionary, I did not encounter any problems and felt very convenient. Through the form of key-value pair, I created – stored – checked whether the Key/Value exists – read – modified/removed maintenance, everything was normal.

Recently, I made a mistake I shouldn’t have made – assignment.

class Program
{      
    static List<List<int>> handCards = new List<List<int> > ();static void Main(string[] args)
    {
	// Declare an assignment
        Dictionary<int.int> dic1 = new Dictionary<int.int> (); dic1.Add(1.1);
        dic1.Add(2.2);
        Dictionary<int.int> dic2 = dic1;
        dic2.Add(3.3);
        dic2.Add(4.4);
        foreach (var item in dic1.Keys)
        {
            Console.WriteLine("dic1 : " + dic1[item]);
        
        }
        foreach (var item in dic2.Keys)
        {
            Console.WriteLine("dic2 : "+ dic2[item]); }}}Copy the code

The way this assignment is done is it points dic2 directly to the memory address of DIC1, which is actually a person with two names, so whoever you call them will respond, so everything you do to DIC1 and DIC2 is a modification of the memory address, which means that changing DIC1 is changing DIC2.

We’ve been exposed to this concept since we first learned about reference types, so it’s almost impossible to make this mistake.

It is important to note that when we use Dic as parameters, traversed to it, try not to outside to add/remove elements of it, otherwise it may encounter the wrong: the Unity of error InvalidOperationException: out of sync.

In another case, when we need more than one operation validation, there are more than one method executing at the same time. Operating on Dic also causes problems.


So, the question is, how do you write an assignment if you think of a value type?

class Program
{      
    static List<List<int>> handCards = new List<List<int> > ();static void Main(string[] args)
    {  			
        // Declare an assignment
        Dictionary<int.int> dic3 = new Dictionary<int.int> (); dic3.Add(1.1);
        dic3.Add(2.2);
        // Equivalent to a value type assignment
        Dictionary<int.int> dic4 = new Dictionary<int.int>(dic3);
        dic4.Add(3.3);
        dic4.Add(4.4);
        foreach (var item in dic3.Keys)
        {
            Console.WriteLine("dic3 : " + dic3[item]);
        }
        foreach (var item in dic4.Keys)
        {
            Console.WriteLine("dic4 : "+ dic4[item]); }}}Copy the code

This way, you can just use the Dictionary value to create a new memory address without affecting it.