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:
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:
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:
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