Difficulty: Easy
Correct Answer: Yes
Explanation:
Introduction / Context:
Many C#.NET design scenarios require controlling who can create objects. A common pattern is to restrict or disable public instantiation to enforce factory patterns, singletons, or utility-only classes. The question asks whether this is possible via the parameterless (zero-argument) constructor.
Given Data / Assumptions:
Concept / Approach:
In C#, access modifiers control visibility. A parameterless constructor declared private (or internal) prevents outside callers from instantiating the class directly. Additional design options include marking the class static (which forbids instance construction entirely) or exposing only factory methods while making constructors non-public.
Step-by-Step Solution:
private Sample()
, code outside the type cannot call new Sample()
.2) Provide static factory methods (for example, Sample Create(...)
) if controlled creation is needed.3) For utility-only types, use static class
; this removes all instance constructors and instance members.4) Optionally combine with sealed to prevent subclass creation paths.
Verification / Alternative check:
Attempt to instantiate from another class with a private parameterless constructor will produce a compile-time error, confirming prevention of external creation.
Why Other Options Are Wrong:
Common Pitfalls:
Assuming a public parameterless constructor is required by the runtime. It is not; you can omit it or make it non-public based on design needs.
Final Answer:
Yes
Discussion & Comments