C#.NET — “Resizing” an array variable from 5 to 10 elements: select the correct approach. If a is an array of 5 integers, choose the correct way to make a refer to a 10-element array (ignoring data preservation).
Correct Answer: int[] a = new int[5]; a = new int[10];
Introduction / Context:Arrays in C# are fixed-size. You cannot change the Length of an existing array instance. To “resize”, you create a new array and make the reference point to it, optionally copying old elements. This question asks which snippet reflects that rule (without requiring data preservation).
Given Data / Assumptions:
- Starting size: 5.
- Target size: 10.
- We only need a to refer to a new 10-element array; copying is out of scope.
Concept / Approach:Because Length is read-only and the array object is immutable in size, you must instantiate a new int[10] and assign it to the same variable. Redeclaring the variable in the same scope is illegal. Methods like GetUpperBound are for querying bounds, not resizing.
Step-by-Step Solution:
Declare: int[] a = new int[5]; Replace: a = new int[10]; // a now references a new array instance.Verification / Alternative check:To preserve data, use Array.Resize(ref a, 10); which internally creates a new array and copies elements.
Why Other Options Are Wrong:
- A redeclares a in the same scope — not valid.
- B is invalid syntax.
- C tries to set Length, which is read-only.
- E calls a query method with the wrong parameter; it does not change size.
Common Pitfalls:Trying to mutate Length, or shadowing the variable in the same scope rather than assigning a new instance.
Final Answer:int[] a = new int[5]; a = new int[10];