Arrays as objects in C# | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Arrays as objects in C#

Why arrays are objects in C#?.I mean why are they ReferenceType,not ValueType?We use RefTypes for dynamic memory allocation,but why for arrays?For example : int[] newArray=new int[4] .We created array which has 4 Int32 elements.So why we store it in a heap?

19th Oct 2019, 12:30 PM
Vitaliy Chernysh
Vitaliy Chernysh - avatar
1 Answer
+ 3
value types are passed by value (as in copied). So if you called a method with a value-type array, you'd be copying all the contents. Stack memory is limited and primarily designed for quick access to parameters that are in current use (as implied by the term stack). Putting a large object onto the stack would cause lookups of other local state to take much longer, because they wouldn't all be on the same cache line in the CPU cache anymore. Array contents are modifiable. So you'd have all the issues that you have with mutable structs when you tried to set a value, only to find that the copy, not the "original" was modified. -you can use stackalloc in unsafe code.
10th Nov 2019, 8:49 PM
mohamed mostafa
mohamed mostafa - avatar