Bird
0
0

Which of these implementations correctly applies this validation?

hard🚀 Application Q15 of 15
C Sharp (C#) - Properties and Encapsulation
You want to create a property Score that only accepts values between 0 and 100 inclusive. If the value is outside this range, it should throw an ArgumentOutOfRangeException. Which of these implementations correctly applies this validation?
Aprivate int score; public int Score { get => score; set { if (value < 0 && value > 100) throw new ArgumentOutOfRangeException("Score must be 0-100"); score = value; } }
Bprivate int score; public int Score { get => score; set { if (value <= 0 && value >= 100) throw new ArgumentOutOfRangeException("Score must be 0-100"); score = value; } }
Cprivate int score; public int Score { get => score; set { if (value > 0 || value < 100) throw new ArgumentOutOfRangeException("Score must be 0-100"); score = value; } }
Dprivate int score; public int Score { get => score; set { if (value < 0 || value > 100) throw new ArgumentOutOfRangeException("Score must be 0-100"); score = value; } }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the range condition

    The value must be between 0 and 100 inclusive, so invalid values are less than 0 or greater than 100.
  2. Step 2: Analyze each condition

    private int score; public int Score { get => score; set { if (value < 0 || value > 100) throw new ArgumentOutOfRangeException("Score must be 0-100"); score = value; } } uses 'value < 0 || value > 100' which correctly checks invalid values. Options A, B, and D use incorrect logical operators or conditions.
  3. Final Answer:

    private int score; public int Score { get => score; set { if (value < 0 || value > 100) throw new ArgumentOutOfRangeException("Score must be 0-100"); score = value; } } -> Option D
  4. Quick Check:

    Use '||' for out-of-range checks [OK]
Quick Trick: Use 'if (value < min || value > max)' for range validation [OK]
Common Mistakes:
MISTAKES
  • Using '&&' instead of '||' in range checks
  • Reversing comparison operators
  • Throwing wrong exception type

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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