C#.NET — Which declarations correctly define a 2×3 rectangular array?
Correct Answer: 1, 3
Introduction / Context:Rectangular arrays in C# specify sizes for each dimension. They can be initialized either with an explicit new int[rows, cols] { ... } or with an implicit = { ... } initializer at declaration time.
Given Data / Assumptions:
- Target array shape is 2 rows × 3 columns.
- We evaluate five candidate declarations/assignments.
Concept / Approach:For rectangular arrays, both of the following are valid: explicit allocation with matching initializer sizes, and declaration with an immediate initializer omitting new int[,]. Incorrect cases either specify wrong dimensions or provide invalid/empty initializers.
Step-by-Step Solution:
1) Valid — explicit 2x3 allocation with a 2×3 initializer.2) Invalid — empty initializer braces are not allowed for a sized array.3) Valid — declaration with initializer infers 2x3.4) Invalid — dimensions are 1×2, not 2×3.5) Invalid — allocation says 1×2 but initializer is 2×3; size mismatch.Verification / Alternative check:Try compiling each snippet; only (1) and (3) succeed for a 2×3 rectangular array.
Why Other Options Are Wrong:
- 2: Empty initializer with fixed size is invalid.
- 4/5: Dimensions do not match the required 2×3 (and 5 also conflicts with its own initializer).
Common Pitfalls:Mixing rectangular arrays with jagged array initialization rules and forgetting zero-based indexing.
Final Answer:1, 3