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

Read-only and write-only properties in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a read-only property in C#?
A read-only property is a property that allows you to get (read) its value but not set (write) it. It has a getter but no setter.
Click to reveal answer
beginner
What is a write-only property in C#?
A write-only property is a property that allows you to set (write) its value but not get (read) it. It has a setter but no getter.
Click to reveal answer
beginner
How do you declare a read-only property in C#?
You declare a read-only property by providing only the get accessor and omitting the set accessor. Example: <br>
public int Age { get; }
Click to reveal answer
intermediate
Can a property be both read-only and write-only at the same time?
No, a property cannot be both read-only and write-only simultaneously because it would mean you can neither read nor write it. It must have at least one accessor.
Click to reveal answer
intermediate
Why would you use a write-only property?
You use a write-only property to allow setting a value without allowing it to be read back. This can be useful for sensitive data like passwords where you want to accept input but not expose the value.
Click to reveal answer
Which accessor(s) does a read-only property have?
AOnly get
BOnly set
CBoth get and set
DNeither get nor set
What happens if you try to read a write-only property?
AYou get the property's value
BThe property returns null
CYou get a compile-time error
DThe program crashes at runtime
How do you declare a write-only property in C#?
AProvide both get and set accessors
BProvide only the get accessor
CProvide neither accessor
DProvide only the set accessor
Why might you want a property to be read-only?
ATo make the property private
BTo prevent external code from changing its value
CTo allow both reading and writing
DTo prevent reading the value
Which of these is a valid read-only property declaration?
Apublic int Value { get; }
Bpublic int Value { set; }
Cpublic int Value { get; set; }
Dpublic int Value { }
Explain how to create a read-only property in C# and why you might use it.
Think about properties that should not be changed after creation.
You got /4 concepts.
    Describe a scenario where a write-only property is useful and how to declare it.
    Consider when you want to accept input but not reveal it.
    You got /4 concepts.