Bird
Raised Fist0

Identify the error in this code snippet:

medium📝 Debug Q6 of Q15
C Sharp (C#) - Classes and Objects
Identify the error in this code snippet:
class Sample {
    private int data;
}
class Program {
    static void Main() {
        Sample s = new Sample();
        Console.WriteLine(s.data);
    }
}
ANo error, code runs fine
BMissing semicolon after class declaration
CClass Sample must be public
DCannot access private field from outside its class
Step-by-Step Solution
Solution:
  1. Step 1: Check access to private field

    The field data is private, so it cannot be accessed from Program class.
  2. Step 2: Identify compilation error

    Trying to access s.data causes compilation error due to access violation.
  3. Final Answer:

    Cannot access private field from outside its class -> Option D
  4. Quick Check:

    Private fields inaccessible outside class [OK]
Quick Trick: Private fields are hidden outside their class [OK]
Common Mistakes:
MISTAKES
  • Thinking private fields are accessible anywhere
  • Assuming missing semicolon error
  • Believing class must be public to access fields

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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