Concept Flow - Property validation logic
Start
Set Property Value
Validate Value
Valid
Assign
End
When setting a property, the value is checked. If valid, it is assigned; if not, an error is raised.
Jump into concepts and practice - no test required
private int age; public int Age { get => age; set { if (value < 0) throw new ArgumentException("Age cannot be negative"); age = value; } }
| Step | Action | Value to Set | Validation Result | Property Value | Exception Thrown |
|---|---|---|---|---|---|
| 1 | Set Age to 25 | 25 | Valid | 25 | None |
| 2 | Set Age to -5 | -5 | Invalid | 25 | ArgumentException: Age cannot be negative |
| 3 | Set Age to 0 | 0 | Valid | 0 | None |
| 4 | Set Age to 100 | 100 | Valid | 100 | None |
| 5 | Set Age to -1 | -1 | Invalid | 100 | ArgumentException: Age cannot be negative |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 | After Step 5 |
|---|---|---|---|---|---|---|
| age | 0 (default) | 25 | 25 | 0 | 100 | 100 |
Property validation logic in C#: - Use a private field to store value. - In the property setter, check the value. - If invalid, throw an exception. - If valid, assign to the field. - This prevents invalid data from being stored.
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;
private string name;
public string Name {
get { return name; }
set {
if (value == null || value == "")
throw new ArgumentException("Name cannot be empty");
name = value;
}
}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?