Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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#)
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#)
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#)
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#)
Hint
Remember to create the Person object, set the ages, and print the final age.
Practice
(1/5)
1. What is the main purpose of adding validation logic inside a property setter in C#?
easy
A. To check and control the value before saving it to the field
B. To make the property read-only
C. To speed up the program execution
D. To automatically generate a default value
Solution
Step 1: Understand property setters
Property setters allow you to assign values to private fields through a controlled interface.
Step 2: Role of validation logic
Validation logic inside the setter checks if the value is valid before saving it, preventing invalid data.
Final Answer:
To check and control the value before saving it to the field -> Option A
Quick Check:
Validation in setter = control value before save [OK]
Hint: Validation logic in setter controls data before saving [OK]
Common Mistakes:
Thinking validation makes property read-only
Assuming validation speeds up code
Confusing validation with default value assignment
2. Which of the following is the correct syntax to throw an exception inside a property setter when the value is invalid?
easy
A. set { if (value < 0) throw new Exception("Invalid value"); field = value; }
B. set { if (value < 0) return; field = value; }
C. set { if (value < 0) Console.WriteLine("Invalid"); field = value; }
Throwing an exception uses the keyword 'throw' followed by 'new Exception(message)'.
Step 2: Check each option
set { if (value < 0) throw new Exception("Invalid value"); field = value; } correctly throws an exception if value is less than zero. Others use invalid statements like return, Console.WriteLine, or break inside setter.
Final Answer:
set { if (value < 0) throw new Exception("Invalid value"); field = value; } -> Option A
Quick Check:
Throw exception = throw new Exception(...) [OK]
Hint: Use 'throw new Exception' to stop invalid values [OK]
Common Mistakes:
Using 'return' instead of 'throw' in setter
Trying to use 'break' inside setter
Only printing error without stopping assignment
3. Consider this C# class snippet:
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;
medium
A. The age is set to -5 without error
B. An ArgumentException is thrown with message 'Age cannot be negative'
C. The program crashes with a NullReferenceException
D. The setter ignores the negative value and leaves age unchanged
Solution
Step 1: Analyze setter validation
The setter checks if value is less than 0 and throws ArgumentException if true.
Step 2: Apply to given code
Setting Age to -5 triggers the exception because -5 < 0.
Final Answer:
An ArgumentException is thrown with message 'Age cannot be negative' -> Option B
Quick Check:
Negative age triggers ArgumentException [OK]
Hint: Setter throws exception on invalid input [OK]
Common Mistakes:
Assuming negative value is accepted
Confusing exception type thrown
Thinking setter silently ignores invalid values
4. Identify the error in this property setter code:
private string name;
public string Name {
get { return name; }
set {
if (value == null || value == "")
throw new ArgumentException("Name cannot be empty");
name = value;
}
}
medium
A. The setter does not assign the value to the field
B. The setter should use 'value.Equals("")' instead of 'value == ""'
C. The setter does not check for whitespace-only strings
D. The setter should not throw exceptions in property setters
Solution
Step 1: Review validation logic
The setter checks if value is null or empty string but does not check if value is whitespace only.
Step 2: Understand missing validation
Strings like " " (spaces) pass the check but are usually invalid for a name.
Final Answer:
The setter does not check for whitespace-only strings -> Option C
Quick Check:
Missing whitespace check in setter validation [OK]
Hint: Check for whitespace with string.IsNullOrWhiteSpace [OK]
Common Mistakes:
Thinking '==' is wrong for string comparison here
Believing exceptions should never be thrown in setters
Forgetting to assign value to field
5. You want to create a property 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?
hard
A. private int score; public int Score { get => score; set { if (value < 0 && value > 100) throw new ArgumentOutOfRangeException("Score must be 0-100"); score = value; } }
B. private int score; public int Score { get => score; set { if (value <= 0 && value >= 100) throw new ArgumentOutOfRangeException("Score must be 0-100"); score = value; } }
C. private int score; public int Score { get => score; set { if (value > 0 || value < 100) throw new ArgumentOutOfRangeException("Score must be 0-100"); score = value; } }
D. private int score; public int Score { get => score; set { if (value < 0 || value > 100) throw new ArgumentOutOfRangeException("Score must be 0-100"); score = value; } }
Solution
Step 1: Understand the range condition
The value must be between 0 and 100 inclusive, so invalid values are less than 0 or greater than 100.
Step 2: Analyze each condition
private int score; public int Score { get => score; set { if (value < 0 || value > 100) throw new ArgumentOutOfRangeException("Score must be 0-100"); score = value; } } uses 'value < 0 || value > 100' which correctly checks invalid values. Options A, B, and D use incorrect logical operators or conditions.
Final Answer:
private int score; public int Score { get => score; set { if (value < 0 || value > 100) throw new ArgumentOutOfRangeException("Score must be 0-100"); score = value; } } -> Option D
Quick Check:
Use '||' for out-of-range checks [OK]
Hint: Use 'if (value < min || value > max)' for range validation [OK]