Bird
0
0

What will be the output of this C# code?

medium📝 Predict Output Q13 of 15
C Sharp (C#) - Classes and Objects
What will be the output of this C# code?
class Counter {
  private int count = 0;
  public void Increment() {
    count++;
  }
  public int GetCount() {
    return count;
  }
}

var c = new Counter();
c.Increment();
c.Increment();
Console.WriteLine(c.GetCount());
A0
B2
C1
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Trace the method calls on the object

    The object c calls Increment() twice, each increasing count by 1.
  2. Step 2: Check the value returned by GetCount()

    After two increments, count is 2, so GetCount() returns 2.
  3. Final Answer:

    2 -> Option B
  4. Quick Check:

    2 increments = count 2 [OK]
Quick Trick: Each Increment adds 1; two calls mean count is 2 [OK]
Common Mistakes:
MISTAKES
  • Forgetting that count starts at 0
  • Assuming Increment does not change count
  • Confusing method return types

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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