Differences between Dictionary.Clear and new Dictionary()

后端 未结 8 835
情书的邮戳
情书的邮戳 2020-12-15 03:33

What are the key differences between Dictionary.Clear and new Dictionary() in C#? Which one is recommended for which cases?

8条回答
  •  北海茫月
    2020-12-15 04:01

    I suppose the key difference is that if you call Dictionary.Clear(), all references to that dictionary will be cleared. If you use new Dictionary(), then the reference you are dealing with at the time will be cleared (in a sense), but all other places you have references won't be since they will still be referring to the old dictionary.

    Hopefully this code illustrates it simply:

    public void Method()
    {
        Dictionary d1 = new Dictionary();
    
        d1.Add(1,1);
        d1.Add(2,3);
    
        Dictionary d2 = d1;
    
        //this line only 'clears' d1
        d1 = new Dictionary();
    
        d1.Add(1,1);
        d1.Add(3,5);
        d2.Add(2,2);
    
        //writes '2' followed by '1'
        Console.WriteLine(d1.Count);
        Console.WriteLine(d2.Count);
    }
    

    If I had called d1.Clear() instead, then d1 and d2 would have remained in sync, and the subsequent adds would have added to both. The WriteLine calls would both have output '3' instead.

提交回复
热议问题