C#.NET — Properties and accessibility: make Console.WriteLine(emp.age) fail by design. Scenario: An Employee class exposes a property named age. There is a reference emp to an Employee object. You want the statement below to fail at compile time (i.e., disallow reading age): Console.WriteLine(emp.age) Which option enforces this? Choose the best design choice.

Difficulty: Easy

Correct Answer: Declare the age property with only a set accessor (write-only property).

Explanation:


Introduction / Context:
This question examines how C#.NET properties control read/write accessibility. The goal is to make a read attempt Console.WriteLine(emp.age) fail at compile time, so you must deny the public getter while still possibly allowing writes.



Given Data / Assumptions:

  • Class: Employee.
  • Property: age.
  • Access attempt: read via Console.WriteLine(emp.age).
  • We want a compile-time error on reading.


Concept / Approach:
In C#, a property can expose a get (read) accessor, a set (write) accessor, both, or neither (with restricted access). A write-only property is made by providing only set and omitting get (or making get less accessible).



Step-by-Step Solution:

To block reads, remove or restrict the get accessor. A write-only property signature looks like: public int age { set { /* validate and assign */ } } Trying to read emp.age causes a compile-time error because get is not defined or not accessible.


Verification / Alternative check:
Try compiling with only set present: any read usage fails, while writes like emp.age = 30; compile.



Why Other Options Are Wrong:

  • A (get only) permits reading, so Console.WriteLine(emp.age) compiles.
  • C exposes both read and write, so reading works (no failure).
  • D “extra accessor” is not a C# concept; only get and set exist.
  • E is wrong because a valid solution exists.


Common Pitfalls:
Confusing access modifiers on get/set with presence of accessors. Even with access modifiers, any accessible get will allow reading.



Final Answer:
Declare the age property with only a set accessor (write-only property).

Discussion & Comments

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