Bird
0
0

Consider the following code:

medium📝 Predict Output Q13 of 15
C Sharp (C#) - Inheritance

Consider the following code:

class Parent {
    protected int number = 5;
}

class Child : Parent {
    public int GetNumber() {
        return number;
    }
}

class Program {
    static void Main() {
        Child c = new Child();
        Console.WriteLine(c.GetNumber());
    }
}

What will be the output when this program runs?

A0
B5
CCompilation error
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Understand protected member access in subclass

    The number field is protected, so the subclass Child can access it directly.
  2. Step 2: Trace the program output

    The GetNumber method returns number which is 5, so Console.WriteLine prints 5.
  3. Final Answer:

    5 -> Option B
  4. Quick Check:

    Protected field accessed in subclass = 5 [OK]
Quick Trick: Protected members accessible in subclass methods [OK]
Common Mistakes:
MISTAKES
  • Thinking protected means inaccessible outside parent
  • Expecting compilation error due to access
  • Confusing protected with private

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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