C#.NET constructors — Choose the correct definitions so that both of the following lines compile and create objects: Sample s1 = new Sample(); Sample s2 = new Sample(9, 5.6f);

Difficulty: Easy

Correct Answer: public Sample()\n{\n i = 0;\n j = 0.0f;\n}\npublic Sample(int ii, Single jj)\n{\n i = ii;\n j = jj;\n}

Explanation:


Introduction / Context:
Overloaded constructors allow different initialization paths. Here, code demonstrates constructing Sample both with no arguments and with two arguments. We must pick the constructor declarations that satisfy both calls.



Given Data / Assumptions:

  • Two object creations: parameterless and (int, Single).
  • C# syntax and types apply; Single is the same as float.


Concept / Approach:
To compile both statements, the class must provide: (1) a parameterless constructor, and (2) a constructor that accepts int and Single. Any option that omits either will fail one of the creations.



Step-by-Step Solution:

Check option A: Defines both Sample() and Sample(int, Single) — satisfies both calls.Option B: Uses a non-C# syntax (Optional keyword is VB-like) — invalid.Option C: Only two-arg constructor present — the new Sample() call fails.Options D/E: Not constructor definitions; they are variable statements.


Verification / Alternative check:
Compiling with only option A present succeeds for both lines. Removing either constructor causes an overload resolution error.



Why Other Options Are Wrong:

  • B: Not valid C# constructor syntax.
  • C: Missing parameterless constructor.
  • D/E: Not constructors at all.


Common Pitfalls:
Confusing VB optional parameter syntax with C# or forgetting that parameterless creation needs an explicit Sample() if any other constructor is declared.



Final Answer:
public Sample() { ... } and public Sample(int, Single) { ... }

Discussion & Comments

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