Properties and Encapsulation
Encapsulation keeps mutation rules close to the state they protect.
How it works
Protect object invariants with validated properties.
A private backing field allows the setter to reject invalid values while callers use natural property syntax.
Runnable C# example
Program.cs
using System;
class Product
{
private decimal _price;
public decimal Price
{
get => _price;
set => _price = value >= 0 ? value : throw new ArgumentOutOfRangeException();
}
}
class Program
{
static void Main()
{
var product = new Product { Price = 19.95m };
Console.WriteLine(product.Price);
}
}
19.95Practice with the debugger
Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.