C#.NET properties — Sample has a Length property with only a set accessor (write-only). Which statements compile and run?

Difficulty: Easy

Correct Answer: Sample m = new Sample(); m.Length = 10;

Explanation:


Introduction / Context:
A write-only property exposes only a set accessor and no get accessor. This question checks whether you can distinguish valid usage of such a property (assignment) from invalid usage (reading the value).



Given Data / Assumptions:

  • Sample.Length exists and has only set.
  • No static property named Length is defined on the type.
  • Standard C# property rules apply.


Concept / Approach:
You can assign to a write-only property on an instance, for example m.Length = 10;. Any attempt to read it (store into a variable, use on the right-hand side, or print it) will not compile because there is no get accessor. Static references like Sample.Length are also invalid unless the property is static (not stated).



Step-by-Step Solution:

Option E: Uses only the setter on an instance → valid.Option A: Attempts to read m.Length → requires get → invalid.Option B: Reads m.Length for the expression → invalid for lack of get.Option C: Tries to set a static property on the type → not given as static → invalid.Option D: Reads a static property → same issue.


Verification / Alternative check:
Define public int Length { set { ... } } and compile; only direct assignments are legal.



Why Other Options Are Wrong:

  • A/B/D: All require a getter.
  • C/D: Also misuse type-qualified access with an instance property.


Common Pitfalls:
Confusing a write-only instance property with a static property; or assuming you can read a value after setting it.



Final Answer:
Sample m = new Sample(); m.Length = 10;

More Questions from Properties

Discussion & Comments

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