Bird
Raised Fist0

What will be the output of this code snippet?

medium📝 Predict Output Q4 of Q15
C Sharp (C#) - Properties and Encapsulation
What will be the output of this code snippet?
class Product {
  private decimal price;
  public decimal Price {
    get => price;
    set {
      if (value < 0) throw new ArgumentOutOfRangeException();
      price = value;
    }
  }
}

var p = new Product();
p.Price = -5;
AThrows ArgumentOutOfRangeException at runtime
BThe price is set to -5 without error
CCompilation error due to invalid setter syntax
DPrice remains 0 silently ignoring -5
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the setter validation logic

    The setter throws ArgumentOutOfRangeException if value is less than 0.
  2. Step 2: Check the assigned value

    Assigning -5 triggers the exception because -5 < 0.
  3. Final Answer:

    Throws ArgumentOutOfRangeException at runtime -> Option A
  4. Quick Check:

    Negative value triggers exception = Throws ArgumentOutOfRangeException at runtime [OK]
Quick Trick: Negative values cause exceptions in validated setters [OK]
Common Mistakes:
MISTAKES
  • Assuming negative values are accepted
  • Confusing compile-time and runtime errors
  • Thinking setter ignores invalid values silently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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