Bird
0
0

What will be the output of the following code?

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

What will be the output of the following code?

class Base {
    protected int value = 10;
}

class Derived : Base {
    public int GetValue() {
        return value;
    }
}

class Program {
    static void Main() {
        Derived d = new Derived();
        System.Console.WriteLine(d.GetValue());
    }
}
A10
BCompilation error
C0
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Understand protected member access

    The 'value' field is protected in Base, accessible in Derived class.
  2. Step 2: Trace method call and output

    GetValue() returns 'value' which is 10; Main prints 10.
  3. Final Answer:

    10 -> Option A
  4. Quick Check:

    Protected member accessed in subclass returns 10 [OK]
Quick Trick: Protected members accessible in subclass methods [OK]
Common Mistakes:
MISTAKES
  • Expecting compilation error due to protected access
  • Confusing default values with protected fields
  • Thinking protected members are inaccessible outside base class

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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