Bird
0
0

What will be the output of the following code?

medium📝 Predict Output Q4 of 15
C Sharp (C#) - Classes and Objects
What will be the output of the following code?
class Test {
    private int x = 5;
    public int GetX() { return x; }
}
class Program {
    static void Main() {
        Test t = new Test();
        Console.WriteLine(t.GetX());
    }
}
A5
BCompilation error
C0
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Understand private field access

    The private field x is not accessible outside Test, but GetX() is public and returns x.
  2. Step 2: Trace the program output

    Main creates Test object and calls GetX(), which returns 5, so Console.WriteLine prints 5.
  3. Final Answer:

    5 -> Option A
  4. Quick Check:

    Private field accessed via public method = 5 [OK]
Quick Trick: Private fields can be accessed via public methods [OK]
Common Mistakes:
MISTAKES
  • Expecting error accessing private field directly
  • Confusing default int value with field value
  • Thinking private blocks all access

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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