C#.NET — Which statement about constructors is correct?

Difficulty: Easy

Correct Answer: If we do not provide a constructor, the compiler provides a zero-argument constructor.

Explanation:


Introduction / Context:
Understanding default constructor generation and constructor rules is fundamental in C#. When you omit constructors, the compiler may synthesize one for you. When you define any constructor, this behavior changes.



Given Data / Assumptions:

  • Focus is on parameterless constructors and special cases like static constructors and optional parameters.


Concept / Approach:
If a class declares no instance constructors at all, the C# compiler provides a public parameterless constructor. However, as soon as you declare at least one instance constructor, the compiler does not generate another parameterless one automatically. Static constructors are parameterless by definition and cannot use optional parameters. Optional parameters are allowed on overloaded instance constructors.



Step-by-Step Solution:

Evaluate A: False — once you provide any constructor, no implicit parameterless constructor is generated.Evaluate B: False — static constructors cannot have parameters (optional or otherwise).Evaluate C: False — overloaded constructors may use optional parameters.Evaluate D: True — with no constructors declared, a default parameterless one is provided.


Verification / Alternative check:
Compile minimal classes with and without explicit constructors to observe presence or absence of a parameterless constructor.



Why Other Options Are Wrong:

  • A: Contradicts the C# rule for default constructor synthesis.
  • B: Violates the definition of static constructors.
  • C: Optional parameters are legal on instance constructors.


Common Pitfalls:
Expecting the compiler to always generate a parameterless constructor even after custom constructors are added.



Final Answer:
If we do not provide a constructor, the compiler provides a zero-argument constructor.

Discussion & Comments

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