Bird
Raised Fist0

What will be the output of this C# code?

medium📝 Predict Output Q5 of Q15
C Sharp (C#) - Classes and Objects
What will be the output of this C# code?
class LightSwitch {
  private bool isOn = false;
  public void Toggle() { isOn = !isOn; }
  public string Status() { return isOn ? "On" : "Off"; }
}

var light = new LightSwitch();
light.Toggle();
light.Toggle();
Console.WriteLine(light.Status());
AOn
BOff
CTrue
DFalse
Step-by-Step Solution
Solution:
  1. Step 1: Trace the Toggle method calls

    Toggle flips isOn from false to true, then true back to false after two calls.
  2. Step 2: Check the Status method output

    Status returns "On" if isOn is true, otherwise "Off". After two toggles, isOn is false.
  3. Final Answer:

    Off -> Option B
  4. Quick Check:

    Toggle twice returns Off status [OK]
Quick Trick: Toggle flips boolean state each call [OK]
Common Mistakes:
MISTAKES
  • Assuming Toggle only sets true
  • Confusing boolean with string output
  • Mixing up true/false with On/Off strings

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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