Skip to content
Codewilds

Lesson 19 of 34 · Classes & Objects

C# Properties: get, set, init and Validation

medium20 XP3 min read

In the last lesson the hero's health was a public field, so any code could write hero.Health = -50. Properties fix that. To the outside world a property looks like a field — you read and assign it with the same syntax — but inside the class it runs code, so the class stays in control of its data. Public data in C# is almost always exposed as a property.

Auto-properties

The shortest form is an auto-implemented property: C# creates the hidden storage for you.

public class Player
{
    public string Name { get; set; } = "";   // read and write
    public int Score { get; private set; }   // anyone reads, only Player writes
    public DateOnly Joined { get; init; }    // can only be set while creating the object

    public void AddPoints(int points) => Score += points;
}

var p = new Player { Name = "Aria", Joined = new DateOnly(2025, 1, 15) };
p.AddPoints(10);
Console.WriteLine(p.Score);   // 10
// p.Score = 999;             // compile error: the setter is private
// p.Joined = ...;            // compile error: init-only

Properties use PascalCase, just like methods.

Computed properties

A property does not have to store anything. A computed (read-only) property calculates its value every time it is read:

public class Rectangle
{
    public double Width { get; set; }
    public double Height { get; set; }
    public double Area => Width * Height;        // expression-bodied getter
    public bool IsSquare => Width == Height;
}

Validation with a backing field

When setting a value needs rules, write the accessors yourself. The classic way uses a private backing field:

public class Thermostat
{
    private int _temperature;

    public int Temperature
    {
        get => _temperature;
        set => _temperature = Math.Clamp(value, 5, 30);   // value is the assigned value
    }
}

var t = new Thermostat();
t.Temperature = 99;
Console.WriteLine(t.Temperature);   // 30

Since C# 14 you can skip the backing field: the field keyword refers to the storage that the compiler generates for the property.

public string Title
{
    get;
    set => field = value.Trim();
} = "";

Fields vs properties

Keep fields private (often named with an underscore, like _temperature) and expose properties. You can later add validation to a property without changing any code that uses it — something you cannot do with a public field.

Common mistakes

  • A setter that assigns the property itself: set => Temperature = value; calls the setter again and again until the program crashes with a stack overflow. Assign the backing field (or field).
  • Making everything { get; set; }: if outside code should not change a value, use private set or init.
  • Expensive work in getters: a property should be quick, like reading a field.

Assignment

Complete the BankAccount class:

  1. Owner (init-only) and Balance (public get, private set) are already declared.
  2. IsEmpty is true when the balance is 0.
  3. Summary returns "<Owner>: <Balance> gold" with two decimals, e.g. "Ann: 50.00 gold".
  4. Deposit(amount) adds positive amounts; 0 or negative amounts are ignored.
  5. Withdraw(amount) subtracts the amount and returns true — but returns false and changes nothing if the amount is not positive or larger than the balance.
  6. Nickname stores the trimmed text, and blank text ("" or only spaces) becomes "Unnamed". A new account's nickname is "Unnamed".

Premium lesson

Unlock the full Learn C# course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Encapsulation and properties in other languages

Need a quick reminder? The C# cheat sheet has every topic of Learn C# on one page.

Lesson last updated on .

Write code ↓
C#+20 XP

Lesson 19 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn C# course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.