C#.NET properties — We want the statement stu.RollNo = 28 to fail for a Student object. How should the rollNo property be declared?

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:

  • Student exposes a property named rollNo.
  • We want external code to read but not write it.

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:

  • A/C: Include a set → the assignment would compile.
  • B: Write-only prevents reading and is not the stated goal.
  • E: There is a correct solution (D).

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

No comments yet. Be the first to comment!
Join Discussion