Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET: Are Dictionary values stored by reference or value

Tags:

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.

like image 734
NSjonas Avatar asked Oct 24 '12 22:10

NSjonas


People also ask

Is dictionary value type or reference type in C#?

It is a class hence it is a Reference Type.

Is dictionary value type or reference type?

In Swift, Array, String, and Dictionary are all value types. They behave much like a simple int value in C, acting as a unique instance of that data.

How does dictionary work in C#?

A dictionary, also called an associative array, is a collection of unique keys and a collection of values, where each key is associated with one value. Retrieving and adding values is very fast. Dictionaries take more memory because for each value there is also a key.

What is the data type for a dictionary in C#?

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.


1 Answers

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

like image 84
zmbq Avatar answered Nov 28 '22 09:11

zmbq