Skip to content

Property accessors

Context: Property accessors (get and set) control how values are read and written. You can apply different access modifiers to each accessor.

private int _value;
public int Value
{
get => _value;
private set => _value = value; // only class can set
}
public string Name { get; } // can be set only in constructor
public string Password { set => /* store */ ; } // no getter

Allows setting only during object initialization.

public class Person
{
public string Name { get; init; }
}
var p = new Person { Name = "Alice" };
// p.Name = "Bob"; // error
public class User
{
public required string UserName { get; set; }
}