C# array memory allocation


New member
Jan 28, 2022
Programming Experience
Why do arrays in c# have fixed size, if they are dynamicly allocated on the heap? Is it just because the reference for the array is allocated on the stack? Does this mean that c++ dynamic arrays are completely allocated on the heap, even their reference?
So what if they are allocated from the heap? Various other objects are also allocated from the heap, would you expect them to also have dynamic sizes? Also the reference to the array may not necessarily be on the stack. If the array is declared within a class, the reference to the array is allocated in the heap within the class instance.

My guess is that the language (and underlying .NET Framework) design was such that arrays would have fixed sizes so that there would be opportunities for the JIT compiler to be able to optimize out of bounds checks, as well as, there would be one less level of indirection. Consider what would happen if an arrays could grow, and but there was no room for growth at its current location: the array would need to be moved to that newer location with the larger space, but you'll need to somehow trick the users of the array into believing that the array is still at the original location.
Top Bottom