Bird
0
0

How can you implement a read-only property Id that is set only once in the constructor using a private field _id?

hard🚀 Application Q9 of 15
C Sharp (C#) - Properties and Encapsulation
How can you implement a read-only property Id that is set only once in the constructor using a private field _id?
Aprivate readonly int _id; public int Id => _id; public ClassName(int id) { _id = id; }
Bprivate int _id; public int Id { get; set; } public ClassName(int id) { Id = id; }
Cpublic int Id { get; private set; } public ClassName(int id) { Id = id; }
Dprivate int _id; public int Id { get { return _id; } set { _id = value; } }
Step-by-Step Solution
Solution:
  1. Step 1: Understand read-only property with private readonly field

    Using a readonly field allows setting value only in constructor.
  2. Step 2: Check options for correct implementation

    private readonly int _id; public int Id => _id; public ClassName(int id) { _id = id; } uses a private readonly field, a getter-only property, and sets the field in constructor.
  3. Final Answer:

    Option A with readonly field and getter-only property. -> Option A
  4. Quick Check:

    Readonly fields set in constructor enable read-only properties [OK]
Quick Trick: Use readonly fields and getter-only properties for read-only data [OK]
Common Mistakes:
MISTAKES
  • Using set accessor making property writable
  • Not using readonly keyword for field
  • Setting property outside constructor

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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