Skip to content

Properties

Context: Properties provide controlled access to private fields using get and set accessors. They encapsulate validation and logic.

private int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
public int Age
{
get => _age;
set => _age = value;
}
public string FullName => $"{FirstName} {LastName}";
private string _secret;
public string Secret { set => _secret = value; }
private int _score;
public int Score
{
get => _score;
set
{
if (value >= 0 && value <= 100)
_score = value;
else
throw new ArgumentOutOfRangeException();
}
}