Difficulty: Easy
Correct Answer: Declare rollNo with only get accessor.
Explanation:
Introduction / Context:To prevent assignment like stu.RollNo = 28; from compiling, the property must be read-only to callers, i.e., it should have a getter but no public setter. This is a common pattern for identifiers.
Given Data / Assumptions:
Concept / Approach:A read-only property is declared with only a get accessor. Optionally, you could provide a private set if the class itself needs to assign internally while callers cannot. Either way, the public API should not expose a set accessor if the goal is to block assignment by outside code.
Step-by-Step Solution:
Define backing field: private int _rollNo;Property: public int RollNo { get { return _rollNo; } }(Optional) public int RollNo { get; private set; } to allow internal writes.Verification / Alternative check:Attempt to compile stu.RollNo = 28; → the compiler reports that there is no set accessor.
Why Other Options Are Wrong:
Common Pitfalls:Exposing a public setter for identifiers can lead to invalid state; prefer immutability or controlled updates.
Final Answer:Declare rollNo with only get accessor.
Discussion & Comments