What is a Property?
In C#, a property provides a flexible mechanism to read, write, or compute the value of a private field. Properties enable encapsulation while exposing a public, intuitive interface.
public class Person
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}Auto‑Implemented Properties
When no additional logic is needed, you can let the compiler create the backing field.
public class Product
{
public int Id { get; set; }
public string Description { get; private set; }
}Getter & Setter Accessors
Accessors can contain custom logic, validation, or computation.
public class Temperature
{
private double _celsius;
public double Celsius
{
get => _celsius;
set
{
if (value < -273.15) throw new ArgumentOutOfRangeException();
_celsius = value;
}
}
public double Fahrenheit
{
get => _celsius * 9 / 5 + 32;
set => Celsius = (value - 32) * 5 / 9;
}
}Access Modifiers
You can apply different accessibility levels to getters and setters.
public class Account
{
public decimal Balance { get; private set; }
public void Deposit(decimal amount) => Balance += amount;
}Examples
Explore common scenarios where properties improve code quality.
Read‑Only Property
public class Circle
{
public double Radius { get; }
public Circle(double r) => Radius = r;
public double Area => Math.PI * Radius * Radius;
}Lazy‑Loading Property
public class DataProvider
{
private string _data;
public string Data
{
get
{
if (_data == null)
_data = LoadData();
return _data;
}
}
private string LoadData() => "Expensive data load...";
}