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

Init-only setters in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an init-only setter in C#?
An init-only setter allows a property to be set only during object initialization, making the property immutable after the object is created.
Click to reveal answer
beginner
How do you declare an init-only property in C#?
Use the init keyword instead of set in the property declaration, like:
public string Name { get; init; }
Click to reveal answer
beginner
When can you assign a value to an init-only property?
You can assign a value only during object creation or in the object initializer block, but not after the object is fully constructed.
Click to reveal answer
intermediate
What happens if you try to set an init-only property after object initialization?
The compiler will give an error because init-only properties cannot be changed after the object is created.
Click to reveal answer
intermediate
Why are init-only setters useful?
They help create immutable objects with simpler syntax, improving safety by preventing accidental changes after creation.
Click to reveal answer
Which keyword is used to declare an init-only setter in C#?
Areadonly
Bset
Cinit
Dconst
When can you assign a value to a property with an init-only setter?
AAnytime after object creation
BOnly in constructors
COnly inside methods
DOnly during object initialization
What will happen if you try to set an init-only property after the object is created?
ACompiler error
BValue changes successfully
CRuntime exception
DProperty is ignored
Which of these is a benefit of using init-only setters?
ACreating immutable objects easily
BAllowing properties to change anytime
CMaking properties private
DImproving runtime performance
How do init-only setters improve code safety?
ABy making properties static
BBy preventing accidental property changes after creation
CBy hiding properties from other classes
DBy allowing properties to be changed anywhere
Explain what init-only setters are and how they differ from regular setters in C#.
Think about when you can assign values to properties.
You got /4 concepts.
    Describe a real-life scenario where using init-only setters would be beneficial.
    Consider objects that should not change after being set up.
    You got /4 concepts.