Tutorials / C# for Beginners / Properties, encapsulation and object initialisers

Properties, encapsulation and object initialisers

12 min read csharp
Course contents (16 lessons)
  1. Getting started
  2. Installing the .NET 10 SDK and checking it works
  3. Your first console app and top-level statements
  4. The building blocks
  5. Variables and basic types
  6. Working with strings and interpolation
  7. Reading input and writing output
  8. Making decisions and repeating work
  9. Conditionals and switch expressions
  10. Loops: for, while, do and foreach
  11. Collections and methods
  12. Arrays and List of T
  13. Writing your own methods
  14. Objects and classes
  15. Classes and objects
  16. Properties, encapsulation and object initialisers
  17. Handling null safely
  18. Errors and files
  19. Exceptions: try, catch, finally and throw
  20. Reading and writing files
  21. Final project: expense tracker
  22. Expense tracker, part 1: planning, model and storage
  23. 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.

  • Name is { get; init; }. The init accessor means the value can be set when the object is created, and never after. The required keyword forces the caller to set it. If you write new Product() without a name, the compiler gives an error.
  • Price has a full body. The value keyword inside the setter is whatever the caller assigned. We reject negative prices by throwing an exception. The backing field _price stores the real value.
  • Stock is 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.
  • InStock and Summary have 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

DeclarationMeaning
{ 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
=> expressionCalculated, 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

  1. Create a Person class with FirstName, LastName (both required and init-only) and a calculated FullName.
  2. Add a BirthYear property that rejects years in the future, and a calculated Age.
  3. Try to assign to FullName and read the compiler error.
csharp
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