Skip to content

From Beginner to Intermediate

The Course
•
30 min study

This course builds a task tracker that saves to a file, sorts with LINQ and is tested without touching a real disk or clock. It assumes that you can write methods, use List<T>, declare classes and records, and handle input that might be wrong. If this first lesson feels unfamiliar, the beginner course covers all of it.

As before, every example runs in your browser. Predict the output before you press Run.

A quick check

This program uses a record, a class with private state and a read-only view. What does it print?

What do you still remember? C#
var shelf = new Shelf();
shelf.Add(new Book("Dune", 412));
shelf.Add(new Book("Emma", 320));

Book copy = new Book("Dune", 412);
Console.WriteLine(copy == shelf.Books[0]);
Console.WriteLine(shelf.Books.Count);
Console.WriteLine(shelf.Books[1] with { Pages = 1 });

record Book(string Title, int Pages);

class Shelf
{
    private readonly List<Book> books = new();

    public IReadOnlyList<Book> Books => books;

    public void Add(Book book)
    {
        books.Add(book);
    }
}
Check your prediction
Text
True
2
Book { Title = Emma, Pages = 1 }

Records compare by value, so the two Dune books are equal even though they're separate objects. with makes a changed copy, and the original stays as it was. If any of that surprised you, reread Days 5 and 6 of the beginner course.

Properties guard their values

A property looks like a field to the code that uses it, but it runs code when you read or write it. That gives a class one place to enforce a rule. value is the incoming value, and field (new in C# 14) is the hidden storage that the compiler makes for the property.

A setter that refuses bad values C#
var timer = new Timer();
timer.Minutes = 25;
Console.WriteLine(timer.Minutes);

try
{
    timer.Minutes = -5;
}
catch (ArgumentOutOfRangeException)
{
    Console.WriteLine("Refused");
}
Console.WriteLine(timer.Minutes);

class Timer
{
    public int Minutes
    {
        get => field;
        set
        {
            ArgumentOutOfRangeException.ThrowIfNegative(value);
            field = value;
        }
    }
}
Check your prediction
Text
25
Refused
25

ThrowIfNegative is a ready-made guard. The assignment fails before field changes, so the object keeps its last good value.

Choosing who can change what

A property's two halves can have different access. Here anyone can read Count, but only the class itself can change it. init allows a value to be set once while the object is being created, and required makes the caller supply it.

Read everywhere, change here C#
var counter = new Counter { Name = "visits" };
counter.Increment();
counter.Increment();
Console.WriteLine($"{counter.Name}: {counter.Count}");

class Counter
{
    public required string Name { get; init; }
    public int Count { get; private set; }

    public void Increment()
    {
        Count++;
    }
}
Check your prediction
Text
visits: 2

Try adding counter.Count = 9; or leaving Name out. Both are compile errors, which is the point: the mistake can't reach a running program.

Fix it: A guard in the wrong place

This timer has a guard, but Minutes still ends up wrong after a refused value. Predict the three lines, then run it.

A guard in the wrong place C#
var timer = new Timer();
timer.Minutes = 25;
Console.WriteLine(timer.Minutes);
try
{
    timer.Minutes = -5;
}
catch (ArgumentOutOfRangeException)
{
    Console.WriteLine("Refused");
}
Console.WriteLine(timer.Minutes);

class Timer
{
    public int Minutes
    {
        get => field;
        set
        {
            field = value;
            ArgumentOutOfRangeException.ThrowIfNegative(value);
        }
    }
}
Check your prediction
Text
25
Refused
-5

The exception was thrown, so the caller was told no, but the bad value had already been stored. Fix the setter so that a refused value leaves the old one in place.

Fix it

Check first, then store. A setter should change nothing until it knows the value is acceptable:

C#
var timer = new Timer();
timer.Minutes = 25;
Console.WriteLine(timer.Minutes);
try
{
    timer.Minutes = -5;
}
catch (ArgumentOutOfRangeException)
{
    Console.WriteLine("Refused");
}
Console.WriteLine(timer.Minutes);

class Timer
{
    public int Minutes
    {
        get => field;
        set
        {
            ArgumentOutOfRangeException.ThrowIfNegative(value);
            field = value;
        }
    }
}
Text
25
Refused
25

The same order matters anywhere state changes: validate everything, then commit. You'll meet it again on Day 5, when a file is saved only after the data is known to be good.

Your turn

Exercise

A temperature that can't go too low

Write a Reading class with a required string Place that can only be set when the object is created, and a double Celsius property. Setting Celsius below -273.15 must throw ArgumentOutOfRangeException and leave the old value alone. Add a read-only property Fahrenheit, worked out as Celsius * 9 / 5 + 32.

Create a reading for Oslo, set 10, print the Fahrenheit value, try to set -300, and print the Celsius value again.

When it works, it prints:

Text
50
Too cold
10
Your workspace C#
Console.WriteLine("Start here");
Hint 1: the idea

The check belongs in the setter of Celsius, before the value is stored. Fahrenheit needs no storage because it can be worked out each time.

Hint 2: a first step

Start with Place and an automatic Celsius property, create the object with an object initializer, then add the guard.

Show one solution
C#
var reading = new Reading { Place = "Oslo" };
reading.Celsius = 10;
Console.WriteLine(reading.Fahrenheit);

try
{
    reading.Celsius = -300;
}
catch (ArgumentOutOfRangeException)
{
    Console.WriteLine("Too cold");
}
Console.WriteLine(reading.Celsius);

class Reading
{
    public required string Place { get; init; }

    public double Celsius
    {
        get => field;
        set
        {
            ArgumentOutOfRangeException.ThrowIfLessThan(value, -273.15);
            field = value;
        }
    }

    public double Fahrenheit => Celsius * 9 / 5 + 32;
}
Text
50
Too cold
10

The guard runs before field = value, so a refused value leaves the old reading in place, which is why the last line still prints 10. Fahrenheit has no setter and no storage: it's worked out from Celsius each time, so the two can never disagree. required with init means a Reading can't exist without a place, and the place can't change afterwards.

Was this article helpful?

Your response is saved on this device.