Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an array of length 1 the same size as a single variable of the same type? [duplicate]

Tags:

arrays

c#

Fairly basic question, imagine

int a = 5;
int[] b = new int[1];
b[0] = 5;

Do both a and b take up the same space in memory? I assume b is larger than a as it has to store the length of itself somewhere, so I thought it would be IntPtr.Size larger, but I am not sure.

I am trying to write code where the length of the array is determined at runtime, and can be 1 or larger (<10). I didn't know if I should just make an array if the length is set to one, or to have a special case in the code and just use the underlying type for length == 1.

I know that a is a value type while b is a reference type.

like image 811
Moop Avatar asked Apr 14 '14 14:04

Moop


1 Answers

No, a and b will not occupy the same amount of memory.

The array container is an object in its own right. It will, somewhere, have to store data pertaining to the number of elements it contains. So it will have a non-zero size.

like image 192
Bathsheba Avatar answered Oct 06 '22 09:10

Bathsheba