What's Behind the Door? An Advent Calendar in C# 15

What's Behind the Door? An Advent Calendar in C# 15
Sarah Dutkiewicz

Sarah Dutkiewicz, Senior Trainer

This post is part of the C# Advent calendar for 2026. Check out all of this year’s posts at csadvent.christmas!

Every December, a little cardboard calendar makes the same promise: one door a day, and something behind each one.

You don’t know what’s behind door 12. But you do know it’s one of a handful of things. Maybe a chocolate. Maybe a tiny toy. Maybe a terrible joke on a slip of paper. Maybe - if a sibling got there first - nothing but cardboard.

“It’s exactly one of these few things” is a type. And until now, C# didn’t have a great way to say it.

Today happens to be December 6th - the feast of St. Nicholas. In many homes, kids set their shoes out last night and woke up to find them filled with treats. Our calendar is getting into the spirit, too: behind door 6, you’ll find a candy cane. (The candy cane’s hook is said to be a nod to a bishop’s crozier, like the one St. Nicholas carried.) It’s a candy cane USB stick, admittedly. This is a developer’s advent calendar, after all.

C# 15 shipped with .NET 11 in November, and it changes that. If you want the deep dives, we’ve got you covered: the Tiles & Tokens series models a board game with unions and closed hierarchies, and Barret’s post on the smaller C# 15 features walks through the rest. This post is the festive version. We’ll build one small advent calendar and open a C# 15 feature (and one gotcha) behind each door.

Everything here was verified on the .NET 11 SDK (11.0.100). A project targeting net11.0 uses C# 15 by default, so there are no preview flags to set.

Door 1: Filling the Calendar

First, we need doors. Each one has a day, a prize, and a flap that’s either open or shut:

public sealed class Door(int day, DoorPrize prize)
{
    public int Day { get; } = day;
    public DoorPrize Prize { get; } = prize;
    public bool IsOpen { get; private set; }

    public DoorPrize Open()
    {
        IsOpen = true;
        return Prize;
    }
}

An advent calendar has exactly 25 doors, and we’re going to add them one at a time. That’s the case where collection expression arguments earn their keep. The new with(...) element passes arguments to the collection’s constructor, so we can size the list up front:

List<Door> calendar = [with(capacity: 25)];

for (int day = 1; day <= 25; day++)
{
    calendar.Add(new Door(day, PrizeFor(day)));
}

Before C# 15, setting a capacity meant falling back to new List<Door>(25), and your code ended up with two styles for creating collections. Now it’s one style. (As Barret points out, the compiler already pre-sizes a collection expression when you spread a source with a known count, so with(capacity:) really shines when you keep adding after creating the list, like we do here.)

Of course, real advent calendars don’t put the doors in order. The numbers are scattered, and half the fun is the hunt. So let’s shuffle the doors into a 5-by-5 grid:

Door[] scattered = [.. calendar];
new Random(2026).Shuffle(scattered);

Door[][] grid = [.. scattered.Chunk(5)];

Door 2: What’s Behind the Door?

Here’s the star of the show. Each door hides exactly one of four things, and C# 15 lets us say so directly with a union type:

public record Chocolate(string Flavor);
public record Toy(string Name);
public record Riddle(string Question, string Answer);
public record Empty;

public union DoorPrize(Chocolate, Toy, Riddle, Empty);

The four case types have nothing in common. A Chocolate doesn’t inherit from anything, and neither does a Toy. They don’t share a base class or an interface. The union is what ties them together.

The compiler gives us an implicit conversion from each case type into the union. That makes stocking the calendar pleasantly boring - every arm of this switch returns a different type, and each one converts to DoorPrize:

string[] flavors = ["peppermint", "milk", "dark", "gingerbread", "salted caramel"];

DoorPrize PrizeFor(int day) => day switch
{
    25 => new Toy("a tiny wooden sleigh"),
    _ when day % 7 == 0 => new Riddle("What carol do developers sing?", "Deck the Halls with Boolean Flags."),
    _ when day % 6 == 0 => new Toy("a candy cane USB stick"),
    _ when day % 11 == 0 => new Empty(),
    _ => new Chocolate(flavors[day % flavors.Length]),
};

Opening a door is a switch expression over the union:

static string Reveal(DoorPrize prize) => prize switch
{
    Chocolate c => $"🍫 A {c.Flavor} chocolate!",
    Toy t => $"🧸 It's {t.Name}!",
    Riddle r => $"❓ {r.Question} {r.Answer}",
    Empty => "📦 Just cardboard. Someone got here first.",
};

Notice what’s missing: there’s no _ => discard arm and no default. The compiler knows a DoorPrize can only be one of four things, so four arms is enough.

And if you forget one? Delete the Empty arm, and the build tells you right away:

warning CS8509: The switch expression does not handle all possible values of its
input type (it is not exhaustive). For example, the pattern 'Empty' is not covered.

That’s the whole pitch for unions. Next year, when the calendar company adds stickers, you add Sticker to the union, and the compiler hands you a list of every place that needs to learn about stickers. No grepping, and no surprises on December 14th.

Door 3: The Door With Nothing Behind It

Every calendar has a dud, and unions have one too.

A union is a struct, which means default(DoorPrize) exists. It isn’t a Chocolate, a Toy, a Riddle, or even an Empty. It’s a door with no cardboard at all, and it matches none of the cases:

DoorPrize nothing = default;

Reveal(nothing); // throws SwitchExpressionException

The compiler won’t warn you about this one. Our Empty case is a deliberate “this door is empty,” and default is an accidental “this door was never filled.” Watch for it anywhere a default value can sneak in - LINQ’s FirstOrDefault over a list of unions is an easy one to miss. We dig into this gotcha in part 2 of Tiles & Tokens.

Door 4: House Rules

Every family has rules about the advent calendar. Some are strict: one door, on its day, no exceptions. Some are forgiving: if you were away for the weekend, you can catch up. And some years, the cousins visit, and all rules are off.

These rules are a different shape than our prizes. They’re all variations of the same idea - a HouseRule - and they could share behavior someday. That’s a job for a closed hierarchy:

public closed record HouseRule;
public record OneDoorADay : HouseRule;
public record CatchUp(int MaxDaysBehind) : HouseRule;
public record CousinsAreVisiting : HouseRule;

The closed modifier says “nobody outside this assembly can derive from HouseRule.” That means the compiler knows every direct descendant, so it can check our switch for exhaustiveness just like it does for a union:

public static bool CanOpen(HouseRule rule, Door door, DateOnly today) => rule switch
{
    OneDoorADay => door.Day == today.Day,
    CatchUp(var maxDaysBehind) => door.Day <= today.Day && door.Day >= today.Day - maxDaysBehind,
    CousinsAreVisiting => true,
};

Add a new rule for the year the twins have to take turns:

public record TwinsTakeTurns : HouseRule;

And the compiler notices before the twins do:

warning CS8509: The switch expression does not handle all possible values of its
input type (it is not exhaustive). For example, the pattern 'TwinsTakeTurns' is not covered.

A closed class is implicitly abstract, so nobody can create a plain HouseRule that isn’t one of the real rules.

Union or closed hierarchy? A quick rule of thumb: if the cases are unrelated types you want to group together (chocolates and riddles), reach for a union. If the cases are related variations of one concept that belong in a class hierarchy (house rules), reach for closed. Part 3 of Tiles & Tokens goes much deeper on that choice.

Door 5: The Hunt for Today’s Door

It’s December 12th. Somewhere in that scattered grid is door 12. Time to hunt.

Searching a grid means nested loops, and nested loops have always had an awkward problem: break only exits the inner loop. In the past, we’d reach for a bool found flag and a second break, or a goto, or extract the whole thing into a method just so we could return from the middle.

C# 15 adds labeled break and continue. Put a label on the loop, then break out of it by name:

DateOnly today = new(2026, 12, 12);

Door? todaysDoor = null;
int checkedCount = 0;

hunt: foreach (Door[] row in grid)
{
    foreach (Door door in row)
    {
        checkedCount++;

        if (door.Day == today.Day)
        {
            todaysDoor = door;
            break hunt;
        }
    }
}

The moment we find door 12, break hunt; leaves both loops. There’s no flag to set, no flag to check, and no “wait, which loop does this exit?”

Labeled continue works the same way, and it’s handy for “stop looking at this row, move on to the next one.” Say a kid wants to know which rows still hide an unopened chocolate. As soon as we find one in a row, the rest of that row doesn’t matter:

List<int> rowsWithChocolate = [];

rows: for (int r = 0; r < grid.Length; r++)
{
    foreach (Door door in grid[r])
    {
        if (!door.IsOpen && door.Prize is Chocolate)
        {
            rowsWithChocolate.Add(r + 1);
            continue rows;
        }
    }
}

That door.Prize is Chocolate check is a pattern match on the union, too.

(Yes, you could write this one with LINQ’s Any. And if your loops get deeply nested, extracting a method is still a fine answer. But when nested loops really are the clearest way to say it, a labeled break beats a Boolean flag. Remember the riddle behind door 7? It’s time to take those Boolean flags down.)

Door 6: calendar[today]

The hunt is fun, but once you know where everything is, you just want to say “give me today’s door.” We could write a GetDoor(DateOnly) method. Or, with C# 15’s extension indexers, we can make the calendar itself indexable by date:

public static class CalendarExtensions
{
    extension(IReadOnlyList<Door> doors)
    {
        public Door this[DateOnly date] =>
            date is { Month: 12, Day: <= 25 }
                ? doors[date.Day - 1]
                : throw new ArgumentOutOfRangeException(nameof(date), "Advent runs December 1-25.");
    }
}

Extension blocks arrived in C# 14, and C# 15 lets them hold indexers, too. Indexers are always instance members, so the extension block needs a named receiver - doors here.

Now this reads like plain English:

Door door = calendar[today];

A few things worth noticing:

  • calendar is a List<Door>, which already has an int indexer. A real instance indexer always wins when it applies. Here it doesn’t, because a DateOnly isn’t an int, so the compiler moves on to our extension.
  • It’s cheap. An indexer looks instant, so it should be instant. Ours is a bounds check and a list lookup. If yours has to walk a sequence or hit a database, make it a method instead.
  • It doesn’t work on arrays. Extension indexers are ignored on arrays and strings, which already have built-in indexing. Try scattered[today] on our shuffled Door[], and you get CS0029: Cannot implicitly convert type 'System.DateOnly' to 'int'. That’s one reason the calendar stays a List<Door>.

Opening Day 12

Let’s put it all together. With today set to December 12th and the house rule set to CatchUp(MaxDaysBehind: 2), we report how the hunt went, then try the doors around today:

Console.WriteLine($"Found door {todaysDoor?.Day} after checking {checkedCount} doors.");

HouseRule rule = new CatchUp(MaxDaysBehind: 2);
foreach (DateOnly date in new[] { today.AddDays(-3), today.AddDays(-2), today, today.AddDays(1) })
{
    Door door = calendar[date];
    string result = HouseRules.CanOpen(rule, door, today) ? Reveal(door.Open()) : "🔒 Not yet!";
    Console.WriteLine($"Door {door.Day,2}: {result}");
}

Here’s the output:

Found door 12 after checking 23 doors.
Door  9: 🔒 Not yet!
Door 10: 🍫 A peppermint chocolate!
Door 12: 🧸 It's a candy cane USB stick!
Door 13: 🔒 Not yet!

Door 12 turned up 23rd out of 25. Of course it did.

Door 9 is three days back, which is past what the catch-up rule allows. Door 13 is tomorrow, so no peeking. And come Christmas morning, calendar[new DateOnly(2026, 12, 25)] gives us the big one:

🧸 It's a tiny wooden sleigh!

Wrapping Up

Behind our six doors, we found:

  1. Collection expression arguments - [with(capacity: 25)] for a list we fill one door at a time
  2. Union types - DoorPrize is exactly one of four unrelated things, with exhaustive matching
  3. The default gotcha - a union nobody filled matches no case at all
  4. Closed hierarchies - HouseRule is a family of related rules the compiler can check completely
  5. Labeled break and continue - hunting through a grid without a Boolean flag in sight
  6. Extension indexers - calendar[today] on a type we didn’t write

None of these features is hard to learn. Together, they let the compiler know a lot more about what’s behind each door, and that’s a gift that keeps on giving all year long.

If this got you curious, the Tiles & Tokens series takes unions and closed hierarchies much further - through System.Text.Json, EF Core 11, and Native AOT - and Barret’s smaller features post covers the rest of C# 15, including a preview of the new unsafe model. And if you’d rather watch than read, curl up with some cocoa and our C# 15 and .NET 11 video playlist on YouTube.

Thanks to the C# Advent organizers for another year of the calendar, and happy holidays from all of us at NimblePros! 🎄

Resources