Bird
Raised Fist0

What will happen if you try to access a protected member from an unrelated class?

medium📝 Predict Output Q5 of Q15
C Sharp (C#) - Inheritance

What will happen if you try to access a protected member from an unrelated class?

class A {
    protected int number = 5;
}

class B {
    void Test() {
        A a = new A();
        System.Console.WriteLine(a.number);
    }
}
APrints 5
BCompilation error due to inaccessible member
CRuntime error
DPrints 0
Step-by-Step Solution
Solution:
  1. Step 1: Identify access context

    Class B is unrelated to A and tries to access protected member 'number'.
  2. Step 2: Understand protected access rules

    Protected members are not accessible from unrelated classes, causing compilation error.
  3. Final Answer:

    Compilation error due to inaccessible member -> Option B
  4. Quick Check:

    Protected members inaccessible from unrelated classes [OK]
Quick Trick: Protected members not accessible from unrelated classes [OK]
Common Mistakes:
MISTAKES
  • Assuming protected members are public
  • Expecting runtime error instead of compile error
  • Trying to access protected members via instance

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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