Domanda

I have a Dictionary<int, Product>. If the same Product is added to more than one key is an new instance of that object stored for each key? Or just a reference to the original object?

This collection is very large and each product will have between 1-10 Keys to it. My primary concern is memory allocation.

È stato utile?

Soluzione

If Product is a reference type (class and not struct), only a reference will be stored.

Altri suggerimenti

No, it should use the same reference to the original object.

I'm not entirely certain how it will behave if the Dictionary is serialized/deserialized, however.

The Dictionary will store a copy of the the value of the key that you pass it. It wouldn't be possible for it, or any other collection/container for that matter, to store a reference to any value as it is possible for the container to outlive the variable that you tried to store in it.

Now, as others have said, if the type of the value is a reference type, the value of the variable is just a reference, so you're just storing a copy of the reference to the variable. If the Type of the value of the dictionary is a value type then the actual value will be copied.

reference types are stored as references always. no one is going to guess what "clone" logic you intend for your type. if you need copies, you will have to create them on your own before placing to containers, passing to other functions and so on.

value types are copied (simplistically byte representation copy is created, however all reference values will still be references), unless passed as ref to functions. for containers though they will be copies. unless you create a reference type wrapper for them.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top