Bird
Raised Fist0

What will be the output of this C# code?

medium📝 Predict Output Q4 of Q15
C Sharp (C#) - Properties and Encapsulation
What will be the output of this C# code?
class Box {
  private int size = 5;
  public int GetSize() { return size; }
}
class Program {
  static void Main() {
    Box b = new Box();
    Console.WriteLine(b.GetSize());
  }
}
A0
B5
CCompilation error
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Understand field and method access

    Private field 'size' is accessed via public method GetSize().
  2. Step 2: Trace method call and output

    GetSize() returns 5, so Console.WriteLine prints 5.
  3. Final Answer:

    5 -> Option B
  4. Quick Check:

    Private field accessed via method = 5 output [OK]
Quick Trick: Private fields accessed via public methods print their values [OK]
Common Mistakes:
MISTAKES
  • Expecting direct access to private field
  • Thinking default int value 0 prints
  • Assuming compilation or runtime error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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