Bird
Raised Fist0

Identify the error in the following code snippet:

medium📝 Debug Q6 of Q15
C Sharp (C#) - Inheritance

Identify the error in the following code snippet:

class Parent {
    protected int data = 100;
}

class Child {
    void Show() {
        Parent p = new Parent();
        System.Console.WriteLine(p.data);
    }
}
ACannot access protected member through an instance of Parent in unrelated class.
BMissing access modifier on Show method.
CParent class must be declared as public.
DNo error, code runs fine.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze access to protected member

    Child class is unrelated to Parent and tries to access protected member via Parent instance.
  2. Step 2: Recall protected access rules

    Protected members cannot be accessed through instances in unrelated classes.
  3. Final Answer:

    Cannot access protected member through an instance of Parent in unrelated class. -> Option A
  4. Quick Check:

    Protected members inaccessible via instance outside inheritance [OK]
Quick Trick: Protected members accessed only inside inheritance, not via instance [OK]
Common Mistakes:
MISTAKES
  • Assuming protected members are accessible via instance
  • Ignoring inheritance requirement
  • Confusing protected with public

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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