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 Sample {
  public int x = 5;
  public void PrintX() {
    int x = 10;
    Console.WriteLine(this.x);
  }
}

var obj = new Sample();
obj.PrintX();
A10
B5
C0
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Identify variable shadowing in method

    The local variable x inside PrintX hides the class field x.
  2. Step 2: Understand this.x usage

    this.x refers to the class field, which is 5, not the local variable 10.
  3. Final Answer:

    5 -> Option B
  4. Quick Check:

    this.x accesses field, not local variable [OK]
Quick Trick: Use this to access hidden fields inside methods [OK]
Common Mistakes:
MISTAKES
  • Printing local variable instead of field
  • Confusing this.x with local x
  • Expecting compilation error due to shadowing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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