Bird
0
0

You want to create a read-only property ID that is set only once during object creation. Which is the best way to declare it using auto-implemented properties?

hard🚀 Application Q8 of 15
C Sharp (C#) - Properties and Encapsulation
You want to create a read-only property ID that is set only once during object creation. Which is the best way to declare it using auto-implemented properties?
Apublic int ID { get; private set; }
Bpublic int ID { private get; set; }
Cpublic int ID { get; set; }
Dpublic int ID { get; }
Step-by-Step Solution
Solution:
  1. Step 1: Understand read-only with set during construction

    Property should allow setting inside the class but not outside.
  2. Step 2: Choose private set accessor

    Using private set allows setting ID inside constructor but read-only outside.
  3. Final Answer:

    public int ID { get; private set; } -> Option A
  4. Quick Check:

    Private set = settable only inside class [OK]
Quick Trick: Use private set for read-only outside class [OK]
Common Mistakes:
MISTAKES
  • Using get only property which can't be set
  • Using public set allowing external changes
  • Misplacing private on get accessor

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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