C#.NET — Array initialization of 4 integers: identify all syntactically correct ways (size and values must be 25, 30, 40, 5). Consider the following five code fragments (numbered 1–5). Which ones correctly define and initialize an array of exactly four integers with values 25, 30, 40, and 5, without indexing errors? int[] a = {25, 30, 40, 5}; int[] a; a = new int[3]; a[0] = 25; a[1] = 30; a[2] = 40; a[3] = 5; int[] a; a = new int{25, 30, 40, 5}; int[] a; a = new int[4]{25, 30, 40, 5}; int[] a; a = new int[4]; a[0] = 25; a[1] = 30; a[2] = 40; a[3] = 5;

Difficulty: Easy

Correct Answer: 1, 4, 5

Explanation:


Introduction / Context:
This question tests your understanding of C# array initialization syntax, array length, and indexing rules. You must recognize which declarations both compile and create a four-element array containing the specified values in the stated order without causing any runtime errors.


Given Data / Assumptions:

  • Target array length: 4.
  • Target values: 25, 30, 40, 5.
  • We must avoid invalid syntax and index-out-of-range writes.


Concept / Approach:
Legal C# forms include implicit-length initialization with braces, or explicit-length with a brace list, or allocate then assign each index within the bounds 0..Length-1. The expression new int{...} is invalid; you must write new int[]{...}. Writing to index 3 on an array created with new int[3] is an out-of-range error because valid indices are 0, 1, and 2.


Step-by-Step Solution:

(1) int[] a = {25, 30, 40, 5}; — Valid; compiler infers length 4. (2) new int[3] then write a[3] — Invalid at runtime (IndexOutOfRangeException). (3) new int{...} — Invalid syntax; missing [] after type. (4) new int[4]{25, 30, 40, 5}; — Valid explicit length and initializer. (5) new int[4] and then assign indices 0..3 — Valid.


Verification / Alternative check:
Compile each snippet separately. (1), (4), and (5) compile and run; (2) compiles but throws when executed; (3) fails to compile due to syntax.


Why Other Options Are Wrong:

  • A includes (2), which writes out of bounds.
  • B includes (3), which is not valid syntax.
  • D includes (2), which fails at runtime; (5) is valid but combined set is not correct.
  • E still includes (2), which is invalid.


Common Pitfalls:
Forgetting that array indices are 0-based; confusing new int{...} with new int[]{...}; and mismatching declared length with the number of assigned elements.


Final Answer:
1, 4, 5

More Questions from Arrays

Discussion & Comments

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