In C#, when can a HotelBooking's GuestName be assigned if it has an init accessor, a private set accessor, or is a readonly field?
answer
- construction phase versus class scope
- object initializer: allowed or not
- CS8852 after construction
- readonly field: initializer or constructor
- compile-time rule only
basics
~20 sAn init accessor is assignable only during creation: an object initializer, a constructor or another init accessor. A private setter works any time, but only inside the class. A readonly field takes its initializer, a constructor or an init accessor.
solid answer
~50 s`init` (C# 9) is a set accessor the compiler lets you call only while the object is being built: in an object initializer such as `new HotelBooking { GuestName = "Ana" }`, on `this` or `base` in an instance constructor, or in another `init` accessor; any later assignment is CS8852. `private set` makes the opposite trade: code outside the class cannot use it, not even in an object initializer (CS0272), but any method of the class can change the value at any time. A get-only auto-property is assignable only in its initializer or a constructor (CS0200 elsewhere), and a `readonly` field in its initializer, a constructor or an `init` accessor of the same type (CS0191 elsewhere). None of them freezes a list the member points to, and `init` does not make callers set the value; `required` does that.
code
csharp · 23 lines#:property PublishAot=false
var booking = new HotelBooking("HB-1042") { GuestName = "Ana Ruiz" };
booking.AddNights(3);
Console.WriteLine($"{booking.Reference} {booking.GuestName} {booking.Nights}");
// booking.GuestName = "Bo Chen"; // error CS8852: init-only after construction
// booking.Nights = 5; // error CS0272: the set accessor is private
// booking.Reference = "HB-9"; // error CS0191: readonly field
// init is enforced by the compiler, not the runtime: reflection still calls the accessor
typeof(HotelBooking).GetProperty(nameof(HotelBooking.GuestName))!.SetValue(booking, "Bo Chen");
Console.WriteLine(booking.GuestName);
public class HotelBooking
{
public readonly string Reference; // initializer, constructor or init accessor
public string GuestName { get; init; } = ""; // object initializer or constructor
public int Nights { get; private set; } // any code inside HotelBooking, at any time
public HotelBooking(string reference) => Reference = reference;
public void AddNights(int count) => Nights += count;
}go deeper
Recall the three rules: init means object initializer or constructor, private set means inside the class at any time, readonly field means its initializer, a constructor or an init accessor.
Explain each rule with its diagnostic, CS8852, CS0272, CS0200 and CS0191, and why only init lets a caller use an object initializer while still blocking later writes.
Point out what these modifiers do not give you: they are shallow, init does not force a value, and reflection-based code can still call an init accessor.
Turn the choice into a team convention: init for caller-supplied immutable data, private set for class-managed state, and required wherever a missing value would be a bug.
## Four ways to limit writes C# gives a class several ways to say who may assign a member and when. They differ on two axes: **who** (callers or only the class) and **when** (only while the object is being created, or at any time). | Declaration | Object initializer from a caller | Constructor | Other methods of the class | Error elsewhere | |---|---|---|---|---| | `string GuestName { get; init; }` | yes | yes | no | CS8852 | | `int Nights { get; private set; }` | no | yes | yes, at any time | CS0272 | | `string Status { get; }` (get-only auto-property) | no | yes | no | CS0200 | | `readonly string Reference` (field) | no | yes, or an `init` accessor | no | CS0191 | ## `init` accessors (C# 9) An `init` accessor is a `set` accessor restricted to the **construction phase**. The compiler accepts an assignment to it only: - in an **object initializer**, `new HotelBooking { GuestName = "Ana Ruiz" }`, from any code that can see the accessor; - on `this` or `base` in an **instance constructor**, including a derived class's constructor assigning an inherited `init` property; - inside another **`init` accessor** of the same object. Anything later, even from a method of the class itself, is CS8852: "Init-only property or indexer 'HotelBooking.GuestName' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor." That is the point of `init`: callers get the readable object-initializer syntax, and the value cannot drift afterwards. ## `private set` `private set` keeps the property writable, but only from code inside the declaring class. It suits state the class itself manages after construction, such as a `Nights` count changed by an `AddNights` method. Two consequences surprise people: - a caller cannot use `private set` from an object initializer; that is CS0272, "the set accessor is inaccessible"; - a derived class cannot assign it either, because `private` means the declaring type only. ## Get-only auto-properties and `readonly` fields A get-only auto-property (`public string Status { get; }`) can be assigned in its initializer or in a constructor of the class, and nowhere else (CS0200). A **`readonly` field** follows the same idea for fields: its variable initializer, any instance constructor, or an `init` accessor of the same type may assign it; anywhere else, including a caller's object initializer, is CS0191. Neither can be set by callers through an object initializer, which is why `init` exists. ## What none of these guarantee - **They are shallow.** `public readonly List<string> Guests = new();` stops anyone replacing the list, not adding to it. The object a member refers to stays as mutable as its own type allows. - **`init` is not "must set".** A caller may skip an `init` property in the initializer and get its default. Forcing a value is the job of the `required` modifier. - **`init` is a compile-time rule.** The compiler marks the accessor with a `modreq` of `System.Runtime.CompilerServices.IsExternalInit` so other compilers respect it, but reflection's `PropertyInfo.SetValue` still invokes it after construction. ## Choosing between them 1. Use **`init`** for values callers supply once, through an object initializer, that must not change afterwards. 2. Use **`private set`** for state the class owns and updates through its own methods. 3. Use a **get-only auto-property** when the value must come through a constructor parameter. 4. Use a **`readonly` field** for private state fixed at construction, such as a reference number or an injected collaborator. In a review of a hotel booking class whose callers set half-built objects, these choices decide which members a caller can touch after `new` returns; whether a caller is forced to supply a value is a separate decision made with `required`. ## Common review findings - **A public `set` where `init` was meant.** `public string GuestName { get; set; }` lets any caller rename the guest of a confirmed booking; `init` keeps the object-initializer syntax and closes that door. - **`private set` used for immutability.** It blocks callers, but the class's own methods can still change the value later; if nothing in the class should, a get-only auto-property or `init` states the intent better. - **A `readonly` field exposed publicly.** It cannot evolve into validated or computed data without the field-to-property break; a get-only property gives the same guarantee to callers and keeps that door open. - **Expecting `init` to validate.** An auto-implemented `init` accessor stores whatever it is given; validation needs an `init` accessor with a body.
- Is an init accessor enforced at run time?No. `init` is a compiler rule: the accessor is emitted with a `modreq` of `IsExternalInit` so compilers that understand it refuse late assignments, but `PropertyInfo.SetValue` through reflection still calls it on a finished object, and serializers that use reflection can too. Treat `init` as protection against mistakes in C# code, not as a security boundary.
- Can a derived class's constructor assign an init property declared in its base class?Yes. CS8852's rule allows assignment on `this` or `base` in an instance constructor, so `public PremiumBooking(string name) { GuestName = name; }` compiles even though `GuestName` is declared in `HotelBooking`. The same assignment from a method of the derived class after construction is still CS8852.
- An init accessor forces callers to set the property in an object initializer.
- A private set accessor can still be used from an object initializer outside the class.
- A readonly field can never change after its field initializer runs.
- Marking a List<T> field readonly stops anyone adding items to it.
- The runtime enforces init, so reflection cannot set an init property later.