Bird
Raised Fist0
C Sharp (C#)programming~10 mins

Property validation logic in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

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
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.
Execution Sample
C Sharp (C#)
private int age;
public int Age {
  get => age;
  set {
    if (value < 0) throw new ArgumentException("Age cannot be negative");
    age = value;
  }
}
This code sets an Age property that throws an error if a negative value is assigned.
Execution Table
StepActionValue to SetValidation ResultProperty ValueException Thrown
1Set Age to 2525Valid25None
2Set Age to -5-5Invalid25ArgumentException: Age cannot be negative
3Set Age to 00Valid0None
4Set Age to 100100Valid100None
5Set Age to -1-1Invalid100ArgumentException: Age cannot be negative
💡 Execution stops after each set attempt; invalid values throw exceptions and do not change the property.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5
age0 (default)25250100100
Key Moments - 3 Insights
Why does the property value not change when an invalid value is set?
Because the validation fails and an exception is thrown before assignment, so the old value remains unchanged (see steps 2 and 5 in execution_table).
What happens if the validation condition is missing?
Without validation, any value can be assigned, including invalid ones, which can cause bugs or unexpected behavior.
Why do we throw an exception instead of just ignoring invalid values?
Throwing an exception immediately alerts the programmer or user that something is wrong, preventing silent errors and making debugging easier.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the property value after step 3?
A25
B0
C100
D-5
💡 Hint
Check the 'Property Value' column for step 3 in the execution_table.
At which step does the validation fail and an exception is thrown?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look for 'Invalid' in 'Validation Result' and 'ArgumentException' in 'Exception Thrown' columns.
If we remove the validation check, what would happen when setting Age to -5?
AAn exception is still thrown
BAge remains unchanged
CAge becomes -5 without error
DThe program crashes immediately
💡 Hint
Without validation, the setter assigns the value directly (see concept_flow).
Concept Snapshot
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.
Full Transcript
This example shows how property validation works in C#. When you try to set a property, the setter checks if the value is valid. If the value is negative for Age, it throws an exception and does not change the stored value. Valid values update the property normally. This helps keep data correct and prevents errors. The execution table shows each step: setting values, validation results, and exceptions if any. The variable tracker shows how the internal age field changes only on valid assignments. Key moments explain why invalid values don't change the property and why exceptions are useful. The quiz tests understanding of these steps.

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

  1. Step 1: Understand property setters

    Property setters allow you to assign values to private fields through a controlled interface.
  2. Step 2: Role of validation logic

    Validation logic inside the setter checks if the value is valid before saving it, preventing invalid data.
  3. Final Answer:

    To check and control the value before saving it to the field -> Option A
  4. 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; }
D. set { if (value < 0) break; field = value; }

Solution

  1. Step 1: Identify correct exception throwing syntax

    Throwing an exception uses the keyword 'throw' followed by 'new Exception(message)'.
  2. 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.
  3. Final Answer:

    set { if (value < 0) throw new Exception("Invalid value"); field = value; } -> Option A
  4. 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

  1. Step 1: Analyze setter validation

    The setter checks if value is less than 0 and throws ArgumentException if true.
  2. Step 2: Apply to given code

    Setting Age to -5 triggers the exception because -5 < 0.
  3. Final Answer:

    An ArgumentException is thrown with message 'Age cannot be negative' -> Option B
  4. 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

  1. Step 1: Review validation logic

    The setter checks if value is null or empty string but does not check if value is whitespace only.
  2. Step 2: Understand missing validation

    Strings like " " (spaces) pass the check but are usually invalid for a name.
  3. Final Answer:

    The setter does not check for whitespace-only strings -> Option C
  4. 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

  1. 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.
  2. 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.
  3. 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
  4. Quick Check:

    Use '||' for out-of-range checks [OK]
Hint: Use 'if (value < min || value > max)' for range validation [OK]
Common Mistakes:
  • Using '&&' instead of '||' in range checks
  • Reversing comparison operators
  • Throwing wrong exception type