Properties
Prerequisites: Constructors
A property looks like a field from the outside but is backed
by get/set accessors — C#'s built-in way to do what Java does
with a manual getBalance()/setBalance() pair, but with field-like
syntax at the call site.
class BankAccount {
private double _balance;
public double Balance {
get => _balance;
set {
if (value < 0) {
throw new ArgumentException("Balance cannot be negative");
}
_balance = value;
}
}
}
var account = new BankAccount();
account.Balance = 100; // calls the setter
Console.WriteLine(account.Balance); // calls the getter — 100
An auto-property skips the backing field entirely when there's no extra logic:
public int Age { get; set; } // fully open
public int Id { get; private set; } // read-only from outside
Common mistakes
- Writing a plain
publicfield where a property (even a simple auto-property) would be more idiomatic — properties let you add validation later without breaking every caller's syntax.