Bird
Raised Fist0

Consider this C# class snippet:

medium📝 Predict Output Q13 of Q15
C Sharp (C#) - Properties and Encapsulation
Consider this C# class snippet:
class Person {
  private int age;
  public int Age {
    get => age;
    set {
      if (value < 0) throw new ArgumentException("Age cannot be negative");
      age = value;
    }
  }
}

What happens if you run this code?
var p = new Person();
p.Age = -5;
AThe age is set to -5 without error
BAn ArgumentException is thrown with message 'Age cannot be negative'
CThe program crashes with a NullReferenceException
DThe setter ignores the negative value and leaves age unchanged
Step-by-Step Solution
Solution:
  1. Step 1: Analyze setter validation

    The setter checks if value is less than 0 and throws ArgumentException if true.
  2. Step 2: Apply to given code

    Setting Age to -5 triggers the exception because -5 < 0.
  3. Final Answer:

    An ArgumentException is thrown with message 'Age cannot be negative' -> Option B
  4. Quick Check:

    Negative age triggers ArgumentException [OK]
Quick Trick: Setter throws exception on invalid input [OK]
Common Mistakes:
MISTAKES
  • Assuming negative value is accepted
  • Confusing exception type thrown
  • Thinking setter silently ignores invalid values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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