C#.NET — For the class below, which object-creation statements will compile? class Sample { int i; Single j; double k; public Sample(int ii, Single jj, double kk) { i = ii; j = jj; k = kk; } }
-
ASample s1 = new Sample();
-
BSample s1 = new Sample(10);
-
CSample s2 = new Sample(10, 1.2f);
-
DSample s3 = new Sample(10, 1.2f, 2.4);
-
ESample s1 = new Sample(, , 2.5);
Answer
Correct Answer: Sample s3 = new Sample(10, 1.2f, 2.4);
Explanation
Introduction / Context:Constructor overload resolution in C# requires a call signature that exactly matches an available constructor's parameter list. The class provides exactly one constructor taking three parameters: int, Single (float), and double.
Given Data / Assumptions:
- Only constructor is
Sample(int, Single, double). - No parameterless or 1–2 parameter overloads exist.
Concept / Approach:Validate each object creation against the available signature. Literal 1.2f is a float, matching Single. A bare 2.4 is a double by default, matching the third parameter.
Step-by-Step Solution:
Option A: Needs parameterless constructor — not available.Option B: Needs a one-argint constructor — not available.Option C: Two-arg call — not available.Option D: Three-arg call with types (int, float, double) — matches declared constructor.Option E: Invalid syntax — commas without arguments are illegal.Verification / Alternative check:Compiling with only the given constructor confirms that only the three-parameter call succeeds.
Why Other Options Are Wrong:
- A/B/C: Missing matching constructor overloads.
- E: Syntax error.
Common Pitfalls:Writing 1.2 without f produces a double, not a float; here we correctly used 1.2f for the Single parameter.
Final Answer:Sample s3 = new Sample(10, 1.2f, 2.4);