Bird
0
0

What will be printed when the following C# program runs?

medium📝 Predict Output Q4 of 15
C Sharp (C#) - Classes and Objects
What will be printed when the following C# program runs?
class Item {
    public static int totalItems = 0;
    public Item() {
        totalItems += 1;
    }
}

class Program {
    static void Main() {
        Item a = new Item();
        Item b = new Item();
        Item c = new Item();
        Console.WriteLine(Item.totalItems);
    }
}
A0
B3
C1
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Understand static field behavior

    The static field totalItems is shared among all instances of Item.
  2. Step 2: Analyze constructor calls

    Each time an Item is created, totalItems increments by 1.
  3. Step 3: Count increments

    Three objects are created, so totalItems becomes 3.
  4. Final Answer:

    3 -> Option B
  5. Quick Check:

    Static field increments with each new object [OK]
Quick Trick: Static fields accumulate changes across all instances [OK]
Common Mistakes:
MISTAKES
  • Assuming static fields reset per instance
  • Confusing instance and static members
  • Expecting zero because no explicit initialization

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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