Bird
Raised Fist0

Consider this class with nested validation:

hard🚀 Application Q9 of Q15
C Sharp (C#) - Properties and Encapsulation
Consider this class with nested validation:
class Employee {
  private string _id;
  public string Id {
    get => _id;
    set {
      if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("Id required");
      if (value.Length != 5) throw new ArgumentException("Id must be 5 chars");
      _id = value;
    }
  }
}

What happens if you assign " " (two spaces) to Id?
AThrows ArgumentException with message "Id must be 5 chars"
BThrows ArgumentException with message "Id required"
CSets _id to " " without error
DCompilation error due to string validation
Step-by-Step Solution
Solution:
  1. Step 1: Understand string.IsNullOrWhiteSpace behavior

    It returns true for strings that are null, empty, or whitespace only.
  2. Step 2: Evaluate the assigned value

    " " is whitespace only, so first condition throws "Id required" exception.
  3. Final Answer:

    Throws ArgumentException with message "Id required" -> Option B
  4. Quick Check:

    Whitespace triggers first validation exception [OK]
Quick Trick: string.IsNullOrWhiteSpace catches empty or spaces [OK]
Common Mistakes:
MISTAKES
  • Assuming whitespace passes validation
  • Expecting second condition to trigger first
  • Confusing compile-time and runtime errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes