Property validation logic
📖 Scenario: You are creating a simple program to store information about a person. You want to make sure the person's age is always a positive number. This means you need to add validation logic to the Age property.
🎯 Goal: Build a Person class with a property Age that only accepts positive numbers. If a negative number or zero is given, the property should keep the old value and not change.
📋 What You'll Learn
Create a class called
Person with a private field age of type int.Add a public property
Age with getter and setter.In the setter of
Age, add validation to accept only values greater than zero.If the value is invalid (zero or negative), do not change the private
age field.Create an instance of
Person and test setting valid and invalid ages.Print the final age to confirm validation works.
💡 Why This Matters
🌍 Real World
Property validation is used in many programs to keep data clean and correct, like ensuring ages, prices, or names are valid.
💼 Career
Understanding property validation is important for writing safe and reliable code in professional software development.
Progress0 / 4 steps