Bird
0
0

Why does C# use init-only setters instead of making properties fully readonly for immutable objects?

hard🧠 Conceptual Q10 of 15
C Sharp (C#) - Properties and Encapsulation
Why does C# use init-only setters instead of making properties fully readonly for immutable objects?
AReadonly properties cannot be set at all, even during initialization.
BInit-only setters allow setting properties during object creation, improving flexibility.
CInit-only setters are faster at runtime than readonly properties.
DReadonly properties allow changes after creation, which is unsafe.
Step-by-Step Solution
Solution:
  1. Step 1: Understand difference between readonly and init-only

    Readonly properties cannot be assigned after declaration; init-only allow assignment during creation.
  2. Step 2: Evaluate reasons for init-only usage

    Init-only setters provide flexibility to set values during initialization while keeping immutability afterward.
  3. Final Answer:

    Init-only setters allow setting properties during object creation, improving flexibility. -> Option B
  4. Quick Check:

    Init-only = flexible initialization, then immutable [OK]
Quick Trick: Init-only lets you set once during creation, unlike readonly [OK]
Common Mistakes:
MISTAKES
  • Thinking readonly allows setting during initialization
  • Assuming init-only is slower than readonly
  • Believing readonly allows changes after creation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes