Practice mode C#

What does an init accessor, as in public string Name { get; init; }, allow in C#?

Correct answer D. The property can be set only during object initialisation, then becomes read-only

Explanation

Init-only setters, added in C# 9, allow assignment in a constructor or an object initialiser such as new Person { Name = "Ali" }, and in with expressions. After the object is constructed, any further assignment is a compile error. This gives immutable objects while keeping the convenient initialiser syntax, and positional record properties use init by default.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.