Complete the code to declare a property with a private setter.
public class Person { public string Name { get; [1] } }
The property setter is made private by using private set, so it can only be set inside the class.
Complete the code to validate the Age property so it cannot be set below 0.
private int age;
public int Age {
get { return age; }
set {
if ([1] < 0) throw new ArgumentException("Age cannot be negative");
age = value;
}
}The value keyword represents the value being assigned to the property. We check if it is less than 0.
Fix the error in the property setter to correctly validate and assign the value.
private string email;
public string Email {
get { return email; }
set {
if (!value.Contains("@"))
throw new ArgumentException("Invalid email");
[1] = value;
}
}The private field email should be assigned the new value, not the property itself, to avoid infinite recursion.
Fill both blanks to create a property that validates the Score is between 0 and 100.
private int score;
public int Score {
get { return score; }
set {
if ([1] < 0 || [2] > 100)
throw new ArgumentOutOfRangeException("Score must be 0-100");
score = value;
}
}We check the new value being assigned (value) to ensure it is within the valid range.
Fill all three blanks to create a property with a backing field that validates non-empty strings and trims whitespace.
private string name;
public string Name {
get { return name; }
set {
if (string.IsNullOrWhiteSpace([1]))
throw new ArgumentException("Name cannot be empty");
name = [2].Trim();
Console.WriteLine($"Name set to: [3]", name);
}
}The setter uses value to check and trim the input. The name field is used in the console output.