Bird
0
0

Identify the error in this C# class that tries to track a score:

medium📝 Debug Q14 of 15
C Sharp (C#) - Classes and Objects
Identify the error in this C# class that tries to track a score:
class Game {
  int score;
  public void AddPoints(int points) {
    score = score + points;
  }
  public int GetScore() {
    return score;
  }
}

var g = new Game();
g.AddPoints(5);
Console.WriteLine(g.GetScore());
ANo error; code runs and prints 5
Bscore should be declared static
CAddPoints method should return int
Dscore is not initialized and may have a default value
Step-by-Step Solution
Solution:
  1. Step 1: Check field initialization rules in C#

    Instance fields like score default to 0 if not explicitly initialized.
  2. Step 2: Verify method behavior and output

    AddPoints adds points correctly, and GetScore returns the updated score. The code prints 5 as expected.
  3. Final Answer:

    No error; code runs and prints 5 -> Option A
  4. Quick Check:

    Uninitialized int defaults to 0 in C# [OK]
Quick Trick: Instance int fields default to 0 if not set [OK]
Common Mistakes:
MISTAKES
  • Thinking uninitialized int fields cause errors
  • Believing AddPoints must return a value
  • Confusing static and instance fields

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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