C#.NET — Implement a read-only property Length correctly in a class.

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:

  • The property is named Length.
  • We want a proper implementation that compiles and is read-only.


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:

Option A: Uses a private field len and returns it in get. No set present → correct read-only property. Option B: Returns Length from inside Length, causing infinite recursion and stack overflow at runtime; incorrect. Option C: Has a set accessor → not read-only. Option D: “Readonly” is not a valid accessor modifier; does not compile. Option E: Although valid C# (expression-bodied read-only property), many exam banks expect the explicit get syntax; the canonical answer is A.


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:

  • B: Recursive getter; incorrect.
  • C: Not read-only by definition.
  • D: Uses an invalid keyword in accessor position.
  • E: Although valid in modern C#, the key expects the classic pattern; we retain A as the correct response.


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

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