Property accessors
Context: Property accessors (get and set) control how values are read and written. You can apply different access modifiers to each accessor.
Different Accessibility
Section titled “Different Accessibility”private int _value;public int Value{ get => _value; private set => _value = value; // only class can set}Getter‑Only Property
Section titled “Getter‑Only Property”public string Name { get; } // can be set only in constructorSetter‑Only Property
Section titled “Setter‑Only Property”public string Password { set => /* store */ ; } // no getterInit Accessor (C# 9+)
Section titled “Init Accessor (C# 9+)”Allows setting only during object initialization.
public class Person{ public string Name { get; init; }}var p = new Person { Name = "Alice" };// p.Name = "Bob"; // errorRequired Properties (C# 11+)
Section titled “Required Properties (C# 11+)”public class User{ public required string UserName { get; set; }}