Bird
Raised Fist0

Find the error in this code:

medium📝 Debug Q7 of Q15
C Sharp (C#) - Properties and Encapsulation
Find the error in this code:
class Product {
  public int Quantity { get; set; }
}

var p = new Product();
p.Quantity = -5;
Console.WriteLine(p.Quantity);
ANo error, code runs and prints -5
BQuantity property missing get accessor
CQuantity property must be readonly
DNegative value assigned without validation
Step-by-Step Solution
Solution:
  1. Step 1: Check property and assignment

    Quantity is an int property with get and set accessors.
  2. Step 2: Identify logical error

    Assigning -5 may be invalid logically but compiles fine; no validation is present.
  3. Final Answer:

    Negative value assigned without validation -> Option D
  4. Quick Check:

    Auto-properties don't validate values automatically [OK]
Quick Trick: Add validation to setters to prevent invalid values [OK]
Common Mistakes:
MISTAKES
  • Expecting compiler error for negative values
  • Assuming auto-properties validate data
  • Ignoring need for manual validation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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