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

Get and set accessors 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 define a property with a get accessor that returns the value of the field.

C Sharp (C#)
private int _age;
public int Age {
    get { return [1]; }
}
Drag options to blanks, or click blank then click option'
AAge
Bthis
Cvalue
D_age
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the property name instead of the field.
Using 'value' inside get accessor.
2fill in blank
medium

Complete the code to define a set accessor that assigns the input value to the field.

C Sharp (C#)
private string _name;
public string Name {
    set { [1] = value; }
}
Drag options to blanks, or click blank then click option'
A_name
Bthis
Cvalue
DName
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning to the property name inside the set accessor causing infinite recursion.
Using 'value' on the left side of assignment.
3fill in blank
hard

Fix the error in the set accessor to correctly assign the value to the field without recursion.

C Sharp (C#)
private double _price;
public double Price {
    set { [1] = value; }
    get { return _price; }
}
Drag options to blanks, or click blank then click option'
A_price
BPrice
Cvalue
Dthis
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning to the property name inside set causing stack overflow.
Using 'value' on the left side.
4fill in blank
hard

Fill both blanks to create a property that only allows setting the field if the value is positive.

C Sharp (C#)
private int _quantity;
public int Quantity {
    get { return _quantity; }
    set {
        if ([1] > 0) {
            [2] = value;
        }
    }
}
Drag options to blanks, or click blank then click option'
Avalue
B_quantity
CQuantity
Dthis
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning to the property name inside set causing recursion.
Checking the field instead of the input value.
5fill in blank
hard

Fill all three blanks to create a property that converts the stored name to uppercase when getting and trims whitespace when setting.

C Sharp (C#)
private string _fullName;
public string FullName {
    get { return [1].ToUpper(); }
    set { [2] = value.[3](); }
}
Drag options to blanks, or click blank then click option'
A_fullName
BFullName
CTrim
DToLower
Attempts:
3 left
💡 Hint
Common Mistakes
Using the property name inside get or set causing recursion.
Using ToLower() instead of Trim() in set.