C#C#
AdvancedLesson 16 of 16

Modern C# 10–12 – C#

Primary constructors, collection expressions, raw strings and more.

C# evolves every year. These new features save boilerplate and make code more readable. Collection expressions (C# 12) create arrays and lists with [...]; the spread operator .. inserts collections. Raw string literals (C# 11) with three quotation marks need no escaping.

int[] a = [1, 2, 3];
List<int> l = [..a, 4, 5];
Console.WriteLine(string.Join(",", l));   // 1,2,3,4,5

string json = """
    {"name": "Ada", "alter": 36}
    """;
Console.WriteLine(json);   // {"name": "Ada", "alter": 36}

var addiere = (int x, int y = 10) => x + y;   // default value in lambda (C# 12)
Console.WriteLine(addiere(5));                 // 15

Primary constructors (C# 12) allow constructor parameters directly in the class header – records already had this, and now normal classes and structs do too. The parameters are available throughout the class body (but they are not automatic properties!).

var z = new Zaehler(5);
z.Erhoehe();
z.Erhoehe();
Console.WriteLine(z.Wert);   // 7

class Zaehler(int start)
{
    private int _wert = start;
    public int Wert => _wert;
    public void Erhoehe() => _wert++;
}

More everyday helpers: aliases for arbitrary types (C# 12), file-scoped namespaces (namespace Meine.App; without indentation), global usings (global using System.Text; once per project) and record struct (value semantics with record convenience).

using Punkt = (int X, int Y);   // must come before all statements

Punkt p = (3, 4);
Console.WriteLine(p.X + p.Y);   // 7

var m = new Meter(5);
Console.WriteLine(m);           // Meter { Wert = 5 }

readonly record struct Meter(int Wert);
TipWhich language version your project uses is determined by the target framework: .NET 8 = C# 12, .NET 9 = C# 13. With <LangVersion>latest</LangVersion> in the .csproj you force the newest version.