# C# 9 and .NET 5: less ceremony, useful improvements

> Records, init-only properties, and ordinary functions make small C# programs easier to read. The runtime improvements are welcome too, but they deserve measurements of their own.

- Author: Deyan Peev (https://deyanpeev.com)
- Published: 2021-06-13
- URL: https://deyanpeev.com/posts/csharp-nine-dotnet-five

I like C# a lot more when I can see the calculation before I see the
architecture. A program that reads some values, applies a rule, and writes a
result should be allowed to look like that.

C# 9 makes that easier. Records remove repetitive data-object code, and
init-only properties let an object initializer finish its work without leaving
every property open for modification. Pattern matching can express a small
decision directly. Top-level statements let a short executable start with what
it does.

None of this means abandoning object-oriented programming. I just get more
choice about how much of it a particular problem needs.

One note on the version names, because they are confusing. The successor to
.NET Core 3.1 is **.NET 5**, while the web framework is still called ASP.NET
Core. This article
uses .NET 5 and C# 9, with SDK 5.0.301 and runtime 5.0.7 from the
[June 8 servicing release](https://devblogs.microsoft.com/dotnet/net-june-2021/).
All of these are released versions.

# Start with data and a rule

Imagine a small utility that summarizes warehouse readings. Each reading has
a location, a temperature, and a flag that says whether the sensor result
is usable. We want the warmest valid reading at each location, classified
against a simple operating range.

There's no database in this example. There's also no reason for a repository
interface, a sensor factory, or a base class representing every conceivable
measurement. Those might become useful in a larger application, but here they
would make us jump between files to find a comparison.

Create a directory with these three files. `global.json` selects the SDK:

```json
{
  "sdk": {
    "version": "5.0.301",
    "rollForward": "disable"
  }
}
```

`Readings.csproj` is the complete project:

```xml
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
    <LangVersion>9.0</LangVersion>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>
```

And this is all of `Program.cs`:

```csharp
using System;
using System.Globalization;
using System.Linq;

var readings = new[]
{
    new Reading("north", 18.5m, true),
    new Reading("north", 22.0m, true),
    new Reading("south", 27.5m, true),
    new Reading("south", 99.0m, false)
};

var summaries = readings
    .Where(reading => reading.IsValid)
    .GroupBy(reading => reading.Location)
    .Select(group => new Summary(group.Key, group.Max(r => r.Celsius)))
    .OrderBy(summary => summary.Location);

foreach (var summary in summaries)
{
    var temperature = summary.Peak.ToString("0.0", CultureInfo.InvariantCulture);
    Console.WriteLine($"{summary.Location}: {temperature} C ({Classify(summary.Peak)})");
}

static string Classify(decimal temperature) => temperature switch
{
    < 16m => "cold",
    >= 16m and <= 25m => "normal",
    > 25m => "warm"
};

public record Reading(string Location, decimal Celsius, bool IsValid);
public record Summary(string Location, decimal Peak);
```

Run `dotnet run --configuration Release`. The result is:

```text
north: 22.0 C (normal)
south: 27.5 C (warm)
```

The invalid 99-degree reading never enters the grouping. The program sorts
its output explicitly, and the formatting doesn't depend on the machine's
decimal separator. Small details, but without them this would be a
demonstration that only happens to work on my laptop.

LINQ isn't new in this release, and neither are local functions or switch
expressions. The new pieces here are the record declarations, the top-level
entry point, and the relational and logical patterns. I mention it because
it's easy to attribute every pleasant line of C# to the latest release.

# Records remove work I would otherwise have to maintain

For these inputs, the values describe the reading, and two readings with equal
components should compare equal. So a record is a reasonable fit.

A positional record provides the constructor and properties, together with
value-based equality and useful printing. I could hand-write those members
on a class, but then I'd have to remember to update all of them when a new
component arrives.

You can insert the following statements before the type declarations in
the example:

```csharp
var original = new Reading("north", 18.5m, true);
var corrected = original with { Celsius = 19.0m };

Console.WriteLine(original == new Reading("north", 18.5m, true));
Console.WriteLine(original.Celsius == 18.5m);
Console.WriteLine(corrected.Celsius == 19.0m);
```

All three expressions print `True`. The correction creates another record,
it doesn't change the original. That's useful when an earlier processing
step still needs the uncorrected input.

The [C# 9 release explanation](https://devblogs.microsoft.com/dotnet/c-9-0-on-the-record/)
describes these semantics, including one limit I would keep in mind, that
copying is shallow. If a record contains a mutable list, copying the record
does not create an independent list. And collection properties don't get
element-by-element equality just because their owner is a record.

The example sticks to strings, decimals, and a Boolean for that reason. Those
values are easy to reason about. For nested mutable objects I'd decide the
ownership and copying rules first and the syntax second.

# Init-only does not mean valid by construction

Sometimes I want an ordinary class with reference identity, but I still want
configuration to stop changing after initialization. `init` does that
without forcing a positional record on the design.

For example, this standalone type could live in `ExportOptions.cs`:

```csharp
public sealed class ExportOptions
{
    public string Separator { get; init; } = ",";
    public bool IncludeHeader { get; init; } = true;
}
```

An initializer can select a semicolon separator, and later code can't assign
another separator through the property. The caller gets a convenient way to
construct the object, and there are no setters that stay available for the
rest of the object's lifetime.

It does not enforce a sensible separator though. A caller could still supply
an empty string. Nullable analysis doesn't replace validation at an input
boundary either. If a type must enforce an invariant, put the check in a
constructor or a dedicated creation function.

I still like conventional objects for this. A type that owns state and
protects meaningful rules can make the rest of a system simpler. A type that
exists only to carry three measurements usually doesn't need that machinery.

# Patterns should make the condition easier to check

The temperature classifier reads as three ranges. I can inspect the lower
boundary, upper boundary, and remaining case without following a method call
into another class. C# 9's `and`, `or`, and `not` patterns help when they
match the vocabulary of the rule.

That doesn't make an elaborate pattern better than an `if`. If a decision
combines configuration, permissions, database state, and an external
response, squeezing it into one expression only makes it harder to debug.
I'd split it into named steps.

For this classifier, the checks that mean something are the boundaries: just
below 16, exactly 16, exactly 25, and just above 25. Testing only 20 would
prove very little. Same for the pipeline. A location with only invalid
readings should disappear, and input order should not determine output order.

I would also keep the data contract explicit if this grew into an importer.
An unknown location, a missing temperature, and a rejected sensor reading are
different conditions, and a short program shouldn't silently collapse them
into the same default value just to keep its expression chain tidy.

# Top-level statements are an entry point, not a filing system

The sample has no explicit `Program.Main`, but it still compiles into an
ordinary executable with an entry point. Type declarations come after the
top-level statements, and only one file in a project can contain that
top-level program.

I find this most useful for importers, diagnostic commands, and small
automation tools, where the first line can tell the reader what the tool
does. When it grows, I can move the calculation into another file without
building a framework around it.

Short isn't the goal though. If this utility starts reading large files,
the grouping operation deserves another look, because it retains data for
the groups and is not a constant-memory streaming maximum. A dictionary
updated as readings arrive might be the better implementation, depending on
the workload.

# The runtime improvements are a separate reason to upgrade

.NET 5 also improves the runtime and libraries. Microsoft's
[performance investigation](https://devblogs.microsoft.com/dotnet/performance-improvements-in-net-5/)
documents changes in the JIT, garbage collection, collections, and other
frequently used paths. Existing code can benefit from these without being
rewritten into the latest syntax.

I would keep two experiments separate. First run the same application on
the old and new runtime with the same workload. Then change the application
code and measure again. Otherwise a faster result tells us very little
about which change helped.

Records are still reference types in C# 9, and making a copy allocates an
object. A pleasant `with` expression is not a memory optimization, and a
cleaner entry point doesn't remove the runtime or make startup free.
For a service, measure startup, allocation rate, throughput, and tail latency
under representative load. For this utility I'd measure total work and peak
memory with a realistic input file.

The [release announcement](https://devblogs.microsoft.com/dotnet/announcing-net-5-0/)
also distinguishes .NET 5 from an LTS release. A team choosing it should have
an upgrade path, because a successful migration isn't the end of runtime
maintenance. Existing .NET Framework applications need a proper compatibility
assessment too. Changing a project target does not port Web Forms or
Windows-only dependencies.
