0Pricing
C# Academy · Lesson

init-Only Setters

Create properties settable only at initialization.

init-Only Setters

An init accessor lets a property be set during object construction (including object initializers) but makes it read-only afterward. The shape is { get; init; }.

using System;

class Point {
    public int X { get; init; }
    public int Y { get; init; }
}

var p = new Point { X = 3, Y = 4 };
Console.WriteLine(p.X + "," + p.Y); // 3,4

Set Only at Initialization

After the object is built, assigning to an init property is a compile error, guaranteeing immutability post-construction.

using System;

class Config {
    public string Name { get; init; }
}

var c = new Config { Name = "prod" };
// c.Name = "dev"; // compile error
Console.WriteLine(c.Name); // prod

All lessons in this course

  1. init-Only Setters
  2. The required Modifier
  3. Immutable Object Patterns
  4. with Expressions on Records
← Back to C# Academy