Bird
0
0

How do you correctly declare a property with an init-only setter in C#?

easy📝 Syntax Q3 of 15
C Sharp (C#) - Properties and Encapsulation
How do you correctly declare a property with an init-only setter in C#?
Apublic string Name { get; set; }
Bpublic string Name { get; init; }
Cpublic string Name { get; private set; }
Dpublic string Name { get; readonly; }
Step-by-Step Solution
Solution:
  1. Step 1: Understand init-only setter syntax

    Init-only setters use the keyword init instead of set to allow assignment only during object initialization.
  2. Step 2: Analyze options

    public string Name { get; init; } correctly uses get; init;. Options B and C use set or private set, which allow modification after initialization. public string Name { get; readonly; } uses an invalid keyword readonly for properties.
  3. Final Answer:

    public string Name { get; init; } -> Option B
  4. Quick Check:

    Init-only setters use init keyword [OK]
Quick Trick: Use 'init' instead of 'set' for init-only properties [OK]
Common Mistakes:
MISTAKES
  • Confusing 'init' with 'set'
  • Using 'readonly' keyword for properties
  • Assuming private set is the same as init

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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