Read or download the complete SDK project, then follow its setup on your computer. The separate C# companion practice below runs in SharpRune’s .NET 9 console environment.
Object and a guard here, a union in C# 15
Parsereturnsobject- A
_ => throwarm guards unknown types - A missing arm is found only at run time
public union Outcome(Accepted, Rejected)- Implicit conversion from each case type
- A missing case arm fails the build (CS8509)
default(Outcome)holdsnull: keep anullarm
Both versions print ok:3, rejected:0, rejected:x and empty. Only the external union lets the compiler prove that Accepted, Rejected and null are every case.
The concept and environment
C# 15 adds union types. A declaration such as union Outcome(Accepted, Rejected) names a closed set of case types, provides an implicit conversion from each one, and lets a switch expression be exhaustive when it handles every case. The case types do not need a common base class or interface. The external .NET 11 project uses a real union. SharpRune's .NET 9 companion returns object and needs a throwing discard arm, which is exactly the gap the new feature closes. It compares results; it does not emulate the compiler.
Walk through the portable program
The companion's Parse accepts only a positive integer. Three becomes an Accepted value, while zero and x become Rejected values carrying the reasons rejected:0 and rejected:x. Describe matches each record type and prints ok:3 for the accepted value. The final call passes null and prints empty. Output is four lines: ok:3, rejected:0, rejected:x and empty. Notice the last arm: because the parameter is object, the compiler cannot know the set of possible types, so the companion must reject unknown values at run time.
Compile the genuine external feature
In the external project, Outcome.cs declares the two records and public union Outcome(Accepted, Rejected). Parse returns either record, and the union conversion wraps it. Describe handles Accepted, Rejected and null with no discard arm. The project file treats warning CS8509, a non-exhaustive switch, as an error, so deleting the Rejected arm stops the build. The generated union is a struct whose Value property holds the case as object, so passing default reaches the null arm. The project targets net11.0 with stable language version 15.0.
Pitfalls and limits
A generated union is always a struct that stores its contents as object, so value-type cases are boxed. Its default value contains null even when every case type is non-nullable, and the compiler does not necessarily warn about a missing null arm; without that arm, a default union throws SwitchExpressionException. A type pattern on a union tests the contents, not the union itself. Unions add no equality, cloning or deconstruction of their own. ASP.NET Core 11 serializes unions in JSON bodies, but not in route, query or header binding.
Practice one: isolate a contract
First, add a third record, Deferred, with a reason, and add it to the union declaration only. Predict the build failure before compiling. Hint: CS8509 names the uncovered pattern, so the compiler points at every switch that needs a new arm. Add the Deferred arm in the external project and the matching arm in the companion. Notice that the companion compiled without the new arm and would have thrown only when a Deferred value arrived, which is the difference between a compile-time contract and a run-time guard.
Practice two: challenge an assumption
For another exercise, remove the null arm from the external Describe and build again. The build succeeds, because the tracked null state of the contents is not null. Run it and observe the exception from the default value. Hint: the warning is absent because nullable analysis trusts the case types, not because a default union is impossible. Restore the arm, then store an Outcome in a new array and describe its first element, which was never assigned. Decide where your own code can produce such default values.
Review the resulting contract
Review a union by listing its case types, the places that construct it, and every switch that consumes it. The declaration fixes the set of alternatives; exhaustiveness then turns a forgotten case into a compile-time error rather than a production exception. Default values still need an explicit decision. Prefer a union when the alternatives share no behavior, and an ordinary class hierarchy when they do. The external project proves the compiler binding; the portable companion keeps the same domain results inspectable on SharpRune's engine, where only the run-time guard protects the switch.
C# 15 union types and exhaustive results lab
Set up the SDK project
- Save every listed file at its exact relative path in a fresh directory.
- Install a .NET 11 SDK supporting stable C# 15; check dotnet --version.
- Run dotnet run --project FeatureLab.csproj. Keep this external code separate from the .NET 9 playground.
Download complete SDK project ↗
Project files
Program.cs
Download file ↗foreach (string text in new[] { "3", "0", "x" }) Console.WriteLine(Describe(Parse(text)));
Console.WriteLine(Describe(default));
static Outcome Parse(string text) =>
int.TryParse(text, out int quantity) && quantity > 0
? new Accepted(quantity)
: new Rejected($"rejected:{text}");
static string Describe(Outcome outcome) => outcome switch
{
Accepted accepted => $"ok:{accepted.Quantity}",
Rejected rejected => rejected.Reason,
null => "empty",
};
Outcome.cs
Download file ↗public sealed record Accepted(int Quantity);
public sealed record Rejected(string Reason);
public union Outcome(Accepted, Rejected);
FeatureLab.csproj
Download file ↗<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net11.0</TargetFramework>
<LangVersion>15.0</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<WarningsAsErrors>CS8509</WarningsAsErrors>
</PropertyGroup>
</Project>
Expected result
Expected console output, in this order: ok:3 rejected:0 rejected:x empty The portable companion compares the same small rule using older syntax; it does not compile or emulate the new feature.
Use the listed SDK and dependencies for this project. Open C# practice runs the separate portable exercise.
C# companion practice
#nullable enable
using System;
foreach (string text in new[] { "3", "0", "x" }) Console.WriteLine(Describe(Parse(text)));
Console.WriteLine(Describe(null));
static object Parse(string text) =>
int.TryParse(text, out int quantity) && quantity > 0
? new Accepted(quantity)
: new Rejected($"rejected:{text}");
static string Describe(object? outcome) => outcome switch
{
Accepted accepted => $"ok:{accepted.Quantity}",
Rejected rejected => rejected.Reason,
null => "empty",
_ => throw new ArgumentException("Unknown outcome.", nameof(outcome)),
};
sealed record Accepted(int Quantity);
sealed record Rejected(string Reason);
C# practice output
ok:3 rejected:0 rejected:x empty
The companion needs a throwing discard arm because object is open. In the external union, delete an arm and read the CS8509 build error.