Does C# dictionary store only the reference of the object or the full copy of the object which is added as key?

爷,独闯天下 提交于 2021-02-10 12:21:53

问题


I want to use a class as key for a dictionary. But the class is large in terms of memory consumption. So, I want to know that when we add an object as key to dictionary, does it only add its reference or full copy is added. As, if the full copy of the object is added then I can just use the hashcode of the object.


回答1:


The dictionary stores whatever value is passed in - that's the case for both the key and the value of the entry. For reference types, that value is a reference - there's no cloning involved to copy the object that the reference refers to. Here's an example:

var dictionary = new Dictionary<int, StringBuilder>();
var builder = new StringBuilder("x");
dictionary.Add(5, builder);

// Retrieve the reference from the dictionary and append to it
dictionary[5].Append("y");

Console.WriteLine(builder); // Prints xy

That's showing the value side of things. The key is stored in the same way - as a reference - but there's a caveat here... if you mutate the object that a key refers to, that's fundamentally going to break the dictionary in most cases, as the hash code of the key is computed when the entry is added. Typically you use immutable types (like string) as keys for dictionaries.




回答2:


Modified answer: The C# Dictionary only stores the references to those Class instances and the Hash Codes of the Key Type. It does not store the actual values themselves.




回答3:


In case of reference types, references to the key and value will be stored in entry struct. The difference between key and value is that we use comparer on the key to keep it unique. The only thing that is copied is the pointer (reference) to the memory where that object is.

Reference type in C#



来源:https://stackoverflow.com/questions/55531617/does-c-sharp-dictionary-store-only-the-reference-of-the-object-or-the-full-copy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!