C#.NET — Arrays: storage location and type hierarchy for int[] a = {11, 3, 5, 9, 4}. Which statements are true? The array elements are created on the stack. The reference variable a is created on the stack (as a local). The array elements are created on the heap. Declaring the array creates a new array class derived from System.Array. Whether the elements are on the stack or heap depends on the array size.

Difficulty: Easy

Correct Answer: 2 and 3 only

Explanation:


Introduction / Context:
This item focuses on where arrays and their elements live in memory and what type the array instance is. Understanding stack vs heap and System.Array inheritance helps avoid common misconceptions about performance and allocation.


Given Data / Assumptions:

  • The example is a local declaration inside a method, e.g., Main.


Concept / Approach:
The local variable a is a reference; local references typically live on the stack (implementation dependent, conceptually a local). The array object, which holds its elements, is always a heap-allocated managed object. Arrays are instances of preexisting runtime-provided types (such as System.Int32[]), which derive from System.Array; we are not creating a new class per declaration.


Step-by-Step Solution:

(1) False — elements are in a heap object, not on the stack. (2) True — the local reference a resides on the stack frame. (3) True — array elements are stored in the heap-allocated array object. (4) False — no new “array class” is created; the array instance's type already exists (System.Int32[]). (5) False — location does not vary with size; arrays are heap objects.


Verification / Alternative check:
Inspect a.GetType() to see System.Int32[]; heap allocation is observable with GC behavior and object identity semantics.


Why Other Options Are Wrong:
They either place elements on the stack, claim class creation, or make storage conditional on size, all contrary to CLR rules.


Common Pitfalls:
Confusing the reference variable's stack storage with where the array and its elements reside.


Final Answer:
2 and 3 only

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion