C#

C# 15: Union types and other new features

Round The Code (David Grace) David Grace
C#

C# 15 adds union types that let the compiler prove a switch is exhaustive, plus closed hierarchies that stop other assemblies from deriving. The post walks through both and weighs a .NET 11 upgrade.

Key points

  • A `union` type lists its allowed cases, so a switch over `StockedProduct` compiles without a default arm.
  • Add CS8509 to `WarningsAsErrors` to turn a non-exhaustive switch into a build failure.
  • `closed` keeps derivation inside the same assembly; CS9382 blocks a base type from another assembly.
  • Union types and closed hierarchies need the .NET 11 runtime; on .NET 10 you get CS0518 and CS0656.
  • `extension` blocks now accept indexers such as this[name], and collection expressions take `with(capacity: ...)` arguments.
  • Labeled `continue nextOrder` skips the inner loop and moves on to the next iteration of the labeled loop.

Real-world use

  • a tax calculation that must cover every product subtype instead of throwing at runtime
  • a NuGet package that wants to give consumers a finite, closed set of types
  • order dispatch code that has to abort the inner loop as soon as a product is out of stock

This summary was generated by the agent from the original post on Round The Code (David Grace). The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message