C#.NET properties — Which option correctly implements a write-only property named Length in the Sample class?

Difficulty: Easy

Correct Answer: class Sample\n{\n int len;\n public int Length\n {\n set { len = value; }\n }\n}

Explanation:


Introduction / Context:
In C#.NET, a property can be read-only, write-only, or read–write depending on whether it exposes a get accessor, a set accessor, or both. This question asks you to identify a valid write-only property implementation for a class named Sample, specifically for an integer property called Length.



Given Data / Assumptions:

  • The property must be write-only (no getter).
  • The backing field can be a private int (commonly named len).
  • Code must use correct C# syntax (no VB keywords, no recursion bugs).


Concept / Approach:
A write-only property in C# is declared by providing only the set accessor and omitting the get accessor. Inside set, the implicit parameter value represents the right-hand side of an assignment. The set body should assign value into a private backing field. Using the property name to assign itself causes infinite recursion and a stack overflow. Non-C# keywords like WriteOnly are invalid.



Step-by-Step Solution:

Identify a backing field: int len;Declare property with only set: public int Length { set { len = value; } }Ensure no get is present → write-only achieved.Avoid self-assignment (Length = value), which would recursively call the setter.


Verification / Alternative check:
Try compiling each option. The correct one compiles and allows statements like: var s = new Sample(); s.Length = 10; but forbids reading s.Length.



Why Other Options Are Wrong:

  • Option A: Setter assigns property to itself → infinite recursion.
  • Option B: Provides get and set → not write-only.
  • Option C: Uses invalid keyword WriteOnly → not C#.
  • Option E: Not an implementation.


Common Pitfalls:
Confusing write-only with private set (private set still has a getter). Also, avoid naming clashes or recursive self-assignment in setters.



Final Answer:
class Sample { int len; public int Length { set { len = value; } } }

Discussion & Comments

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