C#.NET — Using an instance property with get and set: which statements compile and run? Assume class Sample defines a non-static property Length with both get and set accessors. Which of the following statements are valid?

Difficulty: Easy

Correct Answer: 2, 4, 5

Explanation:

Introduction / Context:The problem tests whether you can distinguish between instance versus static property access and evaluate valid reads/writes when a property has both get and set accessors.

Given Data / Assumptions:

  • Length is an instance property of Sample with get and set.
  • Statements:
  • 1) Sample.Length = 20;
  • 2) Sample m = new Sample(); m.Length = 10;
  • 3) Console.WriteLine(Sample.Length);
  • 4) Sample m = new Sample(); int len; len = m.Length;
  • 5) Sample m = new Sample(); m.Length = m.Length + 20;

Concept / Approach:Non-static properties must be accessed through an instance. Reads require get; writes require set. Using the type name for a non-static property does not compile.

Step-by-Step Solution:

1) Invalid: attempts static access; Length is not static. 2) Valid: instance write via m.Length = 10. 3) Invalid: attempts static read; Length is not static. 4) Valid: instance read into len. 5) Valid: reads then writes on the same instance.

Verification / Alternative check:Marking Length as static would change 1 and 3, but the question specifies an instance property, so the provided evaluation stands.

Why Other Options Are Wrong:Any option including 1 or 3 is invalid because they rely on static access.

Common Pitfalls:Confusing static and instance members; assuming properties behave differently than fields with respect to static access.

Final Answer:2, 4, 5

Discussion & Comments

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