Bird
0
0

Which of the following is the correct syntax to add validation logic inside a property setter in C#?

easy📝 Syntax Q3 of 15
C Sharp (C#) - Properties and Encapsulation
Which of the following is the correct syntax to add validation logic inside a property setter in C#?
Aset { if (value < 0) throw new ArgumentException(); _age = value; }
Bset => _age = value if (value >= 0);
Cset { _age = value; if (value < 0) throw new ArgumentException(); }
Dset (value) { if value < 0 throw new ArgumentException(); _age = value; }
Step-by-Step Solution
Solution:
  1. Step 1: Check valid C# setter syntax

    The setter uses curly braces and the keyword 'set' with a block.
  2. Step 2: Validate the order of validation and assignment

    Validation must happen before assigning the value to the backing field.
  3. Final Answer:

    set { if (value < 0) throw new ArgumentException(); _age = value; } -> Option A
  4. Quick Check:

    Setter syntax with validation = set { if (value < 0) throw new ArgumentException(); _age = value; } [OK]
Quick Trick: Validate before assigning in setter block [OK]
Common Mistakes:
MISTAKES
  • Placing assignment before validation
  • Using incorrect setter syntax
  • Missing curly braces for multiple statements

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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