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,4Set 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