Bird
Raised Fist0

Identify the error in this code snippet:

medium📝 Debug Q14 of Q15
C Sharp (C#) - Properties and Encapsulation
Identify the error in this code snippet:
class Car {
  public int speed;
  public int Speed {
    get { return speed; }
    set { speed = value; }
  }
}

var c = new Car();
c.Speed = 50;
Console.WriteLine(c.speed);
AAccessing field directly breaks encapsulation.
BField and property have the same name causing conflict.
CNo error; code works fine.
DProperty must be static to access field.
Step-by-Step Solution
Solution:
  1. Step 1: Check field and property names

    The field is speed and property is Speed, so no naming conflict.
  2. Step 2: Analyze direct field access

    Accessing c.speed directly bypasses the property, which can break encapsulation and safety.
  3. Final Answer:

    Accessing field directly breaks encapsulation. -> Option A
  4. Quick Check:

    Use properties to protect data, not direct field access [OK]
Quick Trick: Avoid direct field access; use properties for safety. [OK]
Common Mistakes:
MISTAKES
  • Thinking same names cause error (case-sensitive).
  • Believing direct field access is always safe.
  • Assuming property must be static.

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes