Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much memory array of objects in c# consumes?

Tags:

arrays

c#

memory

Suppose that we have previously instantiated three objects A, B, C from class D now an array defines as below: D[] arr = new D[3]; arr[0]=A; arr[1]=B; arr[2]=C;

does array contains references to objects or has separate copy?

like image 900
Sali Hoo Avatar asked Aug 26 '10 07:08

Sali Hoo


1 Answers

C# distinguishes reference types and value types.

A reference type is declared using the word class. Variables of these types contain references, so an array will be an array of references to the objects. Each reference is 4 bytes (on a 32-bit system) or 8 bytes (on a 64-bit system) large.

A value type is declared using the word struct. Values of this type are copied every time you assign them. An array of a value type contains copies of the values, so the size of the array is the size of the struct times the number of elements.

Normally when we say “object”, we refer to instances of a reference type, so the answer to your question is “yes”, but remember the difference and make sure that you don’t accidentally create a large array of a large struct.

like image 152
Timwi Avatar answered Oct 03 '22 19:10

Timwi