C#.NET properties — Sample has a Length property with only a get accessor (read-only). Which statements are valid?

Difficulty: Easy

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

Explanation:


Introduction / Context:
A read-only property exposes only a getter. This permits reading the value but forbids assignment. Many .NET APIs use read-only properties for computed or immutable values.



Given Data / Assumptions:

  • Sample.Length has a get accessor and no set accessor.
  • Length is an instance property unless otherwise specified.


Concept / Approach:
With only a getter, you can read the property into a local variable or print it using the instance. You cannot assign to it, nor can you use type-qualified syntax like Sample.Length unless the property is static. Therefore, the only correct option is to construct an instance and read the property value.



Step-by-Step Solution:

Create an instance: var m = new Sample();Read the value: int l = m.Length; → valid with get-only.Attempting assignment m.Length = 10 (A) → invalid (no set).Using m.Length on the right side of an assignment to itself (B) also requires set → invalid.Static access (D, E) would require a static property, which is not stated → invalid.


Verification / Alternative check:
Define public int Length { get { return _len; } } and compile. A and B produce compile-time errors, while C compiles.



Why Other Options Are Wrong:

  • A/B: Attempt to write to a read-only property.
  • D/E: Use type-qualified access without a static property.


Common Pitfalls:
Confusing static and instance members; always access instance properties through an instance unless explicitly static.



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

Discussion & Comments

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