0
0
C Sharp (C#)programming~30 mins

Property validation logic in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the Person class with private age field
Create a class called Person with a private integer field named age initialized to 0.
C Sharp (C#)
Need a hint?

Use private int age = 0; inside the class.

2
Add the Age property with getter and setter
Add a public property called Age with a getter that returns age and a setter that sets age to the given value without validation yet.
C Sharp (C#)
Need a hint?

Use a property with get and set blocks.

3
Add validation logic to the Age setter
Modify the setter of the Age property to only set age if the given value is greater than zero. Otherwise, do not change age.
C Sharp (C#)
Need a hint?

Use an if statement inside the setter to check value > 0.

4
Create a Person instance and test Age property
Create a Person object called person. Set person.Age to 25, then set person.Age to -5. Finally, print person.Age to show the age is still 25.
C Sharp (C#)
Need a hint?

Remember to create the Person object, set the ages, and print the final age.