Object-Oriented C#

Properties and Encapsulation

Protect object invariants with validated properties.

Introduction

Encapsulation keeps mutation rules close to the state they protect.

A private backing field allows the setter to reject invalid values while callers use natural property syntax.

Runnable C# example

C#
Run code →
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);
    }
}
Result of running the code
19.95

Practice 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.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges