Modern C# · Lesson 6

Init-only properties

Construct a value and restrict later assignment.

How it works

An init accessor allows assignment during object initialization but prevents an ordinary assignment after that phase. The required modifier asks callers to supply a value during construction; it does not prove that the supplied string is nonempty or meaningful. In this example the initializer provides both properties, and the later code can read them. These modifiers help communicate construction rules to the compiler.

They do not replace domain validation. If an account code must contain a particular format, use a constructor or factory that checks it and chooses a clear failure result before creating the account.

Remove the Code assignment and run Check to read the compiler message. Restore it, then try an assignment after construction and explain why the init accessor rejects it.

A working example

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

var account = new Account { Code = "A7", Balance = 20m };
Console.WriteLine($"{account.Code}:{account.Balance}");
class Account
{
    public required string Code { get; init; }
    public decimal Balance { get; init; }
}

Expected output

A7:20
Try this
Required means supplied, not validated.