Difficulty: Easy
Correct Answer: class Sample { int len; public int Length { get { return len; } } }
Explanation:
Introduction / Context:
This item tests your ability to recognize a correct read-only property pattern in C#. A read-only property must expose only a get accessor that returns a backing value. Any presence of a set accessor (or infinite self-reference) violates the read-only or correctness requirement.
Given Data / Assumptions:
Concept / Approach:
A traditional read-only property uses a private backing field and provides only a get block that returns that field. Expression-bodied members are also valid modern syntax, but the question typically expects the classic full-property form. Beware of accidental recursion (return Length;) and invalid keywords such as “Readonly” in accessors (not C# syntax).
Step-by-Step Solution:
Verification / Alternative check:
Compiling Option A succeeds; reading Sample.Length returns the stored value of len. Attempts to assign Sample.Length will fail since no setter exists.
Why Other Options Are Wrong:
Common Pitfalls:
Returning the property from itself; forgetting that “readonly” is a field modifier, not an accessor keyword.
Final Answer:
Option A is the correct read-only property implementation.
Discussion & Comments