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

Property validation logic in C Sharp (C#) - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a property with a private setter.

C Sharp (C#)
public class Person {
    public string Name { get; [1] }
}
Drag options to blanks, or click blank then click option'
Aprivate set
Bset
Cget set
Dinit
Attempts:
3 left
💡 Hint
Common Mistakes
Using just 'set' makes the setter public.
Using 'get set' allows public setting.
Using 'init' allows setting only during object initialization.
2fill in blank
medium

Complete the code to validate the Age property so it cannot be set below 0.

C Sharp (C#)
private int age;
public int Age {
    get { return age; }
    set {
        if ([1] < 0) throw new ArgumentException("Age cannot be negative");
        age = value;
    }
}
Drag options to blanks, or click blank then click option'
Athis.age
Bage
Cvalue
DAge
Attempts:
3 left
💡 Hint
Common Mistakes
Using the field name instead of 'value' in the condition.
Using the property name inside its own setter causes recursion.
3fill in blank
hard

Fix the error in the property setter to correctly validate and assign the value.

C Sharp (C#)
private string email;
public string Email {
    get { return email; }
    set {
        if (!value.Contains("@"))
            throw new ArgumentException("Invalid email");
        [1] = value;
    }
}
Drag options to blanks, or click blank then click option'
AEmail
Bemail
Cvalue
Dthis.Email
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning to the property inside its own setter causes infinite recursion.
Assigning to 'value' is invalid.
4fill in blank
hard

Fill both blanks to create a property that validates the Score is between 0 and 100.

C Sharp (C#)
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;
    }
}
Drag options to blanks, or click blank then click option'
Avalue
Bscore
Attempts:
3 left
💡 Hint
Common Mistakes
Using the field name instead of 'value' in the condition.
Checking the wrong variable for the range.
5fill in blank
hard

Fill all three blanks to create a property with a backing field that validates non-empty strings and trims whitespace.

C Sharp (C#)
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);
    }
}
Drag options to blanks, or click blank then click option'
Avalue
Cname
Attempts:
3 left
💡 Hint
Common Mistakes
Using the property name inside its own setter causing recursion.
Using the wrong variable in the Console.WriteLine.