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

Properties vs fields in C Sharp (C#) - Interactive Practice

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

Complete the code to declare a public field named 'age' of type int.

C Sharp (C#)
public class Person {
    public [1] age;
}
Drag options to blanks, or click blank then click option'
Aint
BAge
Cstring
Dprivate
Attempts:
3 left
💡 Hint
Common Mistakes
Using a capitalized name like 'Age' as a type.
Using 'string' instead of 'int' for an age field.
Using access modifiers like 'private' instead of a type.
2fill in blank
medium

Complete the code to declare a public property named 'Age' with get and set accessors.

C Sharp (C#)
public class Person {
    public int [1] { get; set; }
}
Drag options to blanks, or click blank then click option'
Aage
BageValue
CAGE
DAge
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase 'age' for a property name.
Using all uppercase 'AGE' which is uncommon.
Using a different name like 'ageValue' without reason.
3fill in blank
hard

Fix the error in the property declaration by completing the code.

C Sharp (C#)
public class Person {
    private int _age;
    public int Age {
        get { return [1]; }
        set { _age = value; }
    }
}
Drag options to blanks, or click blank then click option'
A_age
BAge
Cvalue
Dage
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the property name 'Age' inside its own getter causes recursion.
Returning 'value' inside getter is incorrect.
Using 'age' without underscore when the field is '_age'.
4fill in blank
hard

Fill both blanks to create a property 'Name' with a private field '_name' and a setter that trims whitespace.

C Sharp (C#)
public class Person {
    private string [1];
    public string Name {
        get { return [2]; }
        set { [2] = value.Trim(); }
    }
}
Drag options to blanks, or click blank then click option'
A_name
BName
C_age
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using the property name 'Name' inside getter or setter causes recursion.
Using a different field name in getter and setter.
Not trimming the value in setter.
5fill in blank
hard

Fill all three blanks to create a read-only property 'IsAdult' that returns true if 'Age' is 18 or more.

C Sharp (C#)
public class Person {
    public int Age { get; set; }
    public bool [1] {
        get { return Age [2] [3]; }
    }
}
Drag options to blanks, or click blank then click option'
AIsAdult
B>=
C18
DAge
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Age' as property name instead of 'IsAdult'.
Using '<' or '>' instead of '>='.
Comparing to a wrong number.