Properties, encapsulation and object initialisers
Course contents (16 lessons)
- Getting started
- Installing the .NET 10 SDK and checking it works
- Your first console app and top-level statements
- The building blocks
- Variables and basic types
- Working with strings and interpolation
- Reading input and writing output
- Making decisions and repeating work
- Conditionals and switch expressions
- Loops: for, while, do and foreach
- Collections and methods
- Arrays and List of T
- Writing your own methods
- Objects and classes
- Classes and objects
- Properties, encapsulation and object initialisers
- Handling null safely
- Errors and files
- Exceptions: try, catch, finally and throw
- Reading and writing files
- Final project: expense tracker
- Expense tracker, part 1: planning, model and storage
- Expense tracker, part 2: the menu and summaries
The problem with public fields
In the last lesson we used public fields for Name and Age. That is risky. Anyone can set Age to -5, and the class cannot stop them. If you later want to add a rule, you must change a field into something else, and every piece of code that used it may break.
C# solves this with properties. A property looks like a field to the code that uses it, but it is really a pair of small methods: a getter and a setter. You can add rules later without changing the callers.
Auto-properties and rules
The simplest property is an auto-property. The compiler creates a hidden field for you.
var product = new Product
{
Name = "Notebook",
Price = 120m,
Stock = 15
};
product.Stock -= 5;
Console.WriteLine(product.Summary);
try
{
product.Price = -10m;
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"Rejected: {ex.ParamName}");
}
var order = new Order("A-1001");
order.Confirm();
Console.WriteLine($"{order.Number} confirmed: {order.IsConfirmed}");
// order.Number = "X"; // does not compile, init-only
class Product
{
private decimal _price;
public required string Name { get; init; }
public decimal Price
{
get => _price;
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(Price), "Price cannot be negative.");
}
_price = value;
}
}
public int Stock { get; set; }
public bool InStock => Stock > 0;
public string Summary => $"{Name}: {Price:N2} each, {Stock} in stock";
}
class Order
{
public Order(string number)
{
Number = number;
}
public string Number { get; }
public bool IsConfirmed { get; private set; }
public void Confirm() => IsConfirmed = true;
}
Walking through it
The Product class shows four kinds of property.
Nameis{ get; init; }. Theinitaccessor means the value can be set when the object is created, and never after. Therequiredkeyword forces the caller to set it. If you writenew Product()without a name, the compiler gives an error.Pricehas a full body. Thevaluekeyword inside the setter is whatever the caller assigned. We reject negative prices by throwing an exception. The backing field_pricestores the real value.Stockis a plain auto-property. Anyone can read or write it. I accept that here because no rule applies. Compare that with a public field: if you decide later to log changes or add a rule, a property lets you do it without touching callers.InStockandSummaryhave only a getter written with=>. They are calculated every time you read them and store nothing.
The object initialiser syntax, new Product { Name = ..., Price = ... }, sets properties right after construction. It reads clearly, and it saves you from writing a constructor with six parameters.
The Order class shows two more ideas. Number has only a getter, so it can be set only in the constructor. IsConfirmed has a private setter. Everybody can read it, but only Order itself can change it, and it does so through Confirm. This is the pattern I use most for state that must change by rules.
When to use which
| Declaration | Meaning |
|---|---|
{ get; set; } | Read and write from anywhere |
{ get; private set; } | Read from anywhere, change only inside the class |
{ get; init; } | Set once while creating the object |
{ get; } | Set only in the constructor |
=> expression | Calculated, no storage |
Common mistakes
- Writing a property that calls itself. A setter that does
Price = value;calls itself forever and crashes. Assign the backing field instead. - Doing slow work in a getter. People assume reading a property is cheap. Use a method if it is not.
- Making everything
set. Start with the narrowest accessor you can.
Try it yourself
- Create a
Personclass withFirstName,LastName(both required and init-only) and a calculatedFullName. - Add a
BirthYearproperty that rejects years in the future, and a calculatedAge. - Try to assign to
FullNameand read the compiler error.
var product = new Product
{
Name = "Notebook",
Price = 120m,
Stock = 15
};
product.Stock -= 5;
Console.WriteLine(product.Summary);
try
{
product.Price = -10m;
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"Rejected: {ex.ParamName}");
}
var order = new Order("A-1001");
order.Confirm();
Console.WriteLine($"{order.Number} confirmed: {order.IsConfirmed}");
// order.Number = "X"; // does not compile, init-only
class Product
{
private decimal _price;
public required string Name { get; init; }
public decimal Price
{
get => _price;
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(Price), "Price cannot be negative.");
}
_price = value;
}
}
public int Stock { get; set; }
public bool InStock => Stock > 0;
public string Summary => $"{Name}: {Price:N2} each, {Stock} in stock";
}
class Order
{
public Order(string number)
{
Number = number;
}
public string Number { get; }
public bool IsConfirmed { get; private set; }
public void Confirm() => IsConfirmed = true;
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account