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#?
✗ Incorrect
The
init keyword declares a setter that can only be used during object initialization.When can you assign a value to a property with an init-only setter?
✗ Incorrect
Init-only setters allow assignment only during object initialization or in the initializer block.
What will happen if you try to set an init-only property after the object is created?
✗ Incorrect
The compiler prevents setting init-only properties after initialization, causing a compile-time error.
Which of these is a benefit of using init-only setters?
✗ Incorrect
Init-only setters help create immutable objects by restricting property changes after initialization.
How do init-only setters improve code safety?
✗ Incorrect
They prevent accidental changes to properties after the object is created, improving safety.
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.