Introduction
Property validation logic helps check if the values given to an object are correct. It stops wrong data from being saved.
Jump into concepts and practice - no test required
Property validation logic helps check if the values given to an object are correct. It stops wrong data from being saved.
private int _age; public int Age { get { return _age; } set { if (value < 0) throw new ArgumentException("Age cannot be negative"); _age = value; } }
The get part reads the value.
The set part checks the value before saving it.
private string _name; public string Name { get => _name; set { if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("Name cannot be empty"); _name = value; } }
private int _score; public int Score { get => _score; set => _score = (value >= 0 && value <= 100) ? value : throw new ArgumentOutOfRangeException("Score must be 0-100"); }
This program tries to set a valid age first, then tries an invalid age. It catches and shows the error message.
using System; class Person { private int _age; public int Age { get => _age; set { if (value < 0) throw new ArgumentException("Age cannot be negative"); _age = value; } } } class Program { static void Main() { var p = new Person(); try { p.Age = 25; Console.WriteLine($"Age set to: {p.Age}"); p.Age = -5; // This will cause error } catch (ArgumentException e) { Console.WriteLine($"Error: {e.Message}"); } } }
Always validate data to keep your program safe and correct.
Throwing exceptions helps you find errors early.
You can also use other ways like returning error codes, but exceptions are common in C#.
Property validation checks values before saving them.
Use get and set to control property access.
Throw exceptions to stop wrong data and show clear errors.
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?