-
Notifications
You must be signed in to change notification settings - Fork 6.1k
Add language reference for union types (C# 15)
#52485
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
BillWagner
wants to merge
13
commits into
dotnet:main
Choose a base branch
from
BillWagner:union-fundamentals
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+733
−34
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
6f8ca3d
Publish unions speclet
BillWagner ac5739b
First draft of unions reference.
BillWagner 640e3f6
Refactor sample
BillWagner 72d7215
Content edit on main article.
BillWagner 7db55b4
Update existing docs
BillWagner 0af581f
Add other links for `union` types
BillWagner 60f1e8b
proofread minor edits
BillWagner 3899230
2nd drafts.
BillWagner 3a390da
use polyfill snippet
BillWagner c9a9a14
Apply suggestions from code review
BillWagner fa5e2d0
build fixes
BillWagner 09dc47a
Point out upcoming features.
BillWagner e8d07db
feedback
BillWagner File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
44 changes: 44 additions & 0 deletions
44
docs/csharp/language-reference/builtin-types/snippets/unions/BasicUnion.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| // <CaseTypes> | ||
| public record class Cat(string Name); | ||
| public record class Dog(string Name); | ||
| public record class Bird(string Name); | ||
| // </CaseTypes> | ||
|
|
||
| // <BasicDeclaration> | ||
| public union Pet(Cat, Dog, Bird); | ||
| // </BasicDeclaration> | ||
|
|
||
| public static class BasicUnionScenario | ||
| { | ||
| public static void Run() | ||
| { | ||
| BasicConversion(); | ||
| PatternMatching(); | ||
| } | ||
|
|
||
| // <BasicConversion> | ||
| static void BasicConversion() | ||
| { | ||
| Pet pet = new Dog("Rex"); | ||
| Console.WriteLine(pet.Value); // output: Dog { Name = Rex } | ||
|
|
||
| Pet pet2 = new Cat("Whiskers"); | ||
| Console.WriteLine(pet2.Value); // output: Cat { Name = Whiskers } | ||
| } | ||
| // </BasicConversion> | ||
|
|
||
| // <PatternMatching> | ||
| static void PatternMatching() | ||
| { | ||
| Pet pet = new Dog("Rex"); | ||
|
|
||
| var name = pet switch | ||
| { | ||
| Dog d => d.Name, | ||
| Cat c => c.Name, | ||
| Bird b => b.Name, | ||
| }; | ||
| Console.WriteLine(name); // output: Rex | ||
| } | ||
| // </PatternMatching> | ||
| } |
30 changes: 30 additions & 0 deletions
30
docs/csharp/language-reference/builtin-types/snippets/unions/BodyMembers.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| // <BodyMembers> | ||
| public union OneOrMore<T>(T, IEnumerable<T>) | ||
| { | ||
| public IEnumerable<T> AsEnumerable() => Value switch | ||
| { | ||
| T single => [single], | ||
| IEnumerable<T> multiple => multiple, | ||
| _ => [] | ||
| }; | ||
| } | ||
| // </BodyMembers> | ||
|
|
||
| public static class BodyMembersScenario | ||
| { | ||
| public static void Run() | ||
| { | ||
| BodyMembersExample(); | ||
| } | ||
|
|
||
| // <BodyMembersExample> | ||
| static void BodyMembersExample() | ||
| { | ||
| OneOrMore<string> single = "hello"; | ||
| OneOrMore<string> multiple = new[] { "a", "b", "c" }.AsEnumerable(); | ||
|
|
||
| Console.WriteLine(string.Join(", ", single.AsEnumerable())); // output: hello | ||
| Console.WriteLine(string.Join(", ", multiple.AsEnumerable())); // output: a, b, c | ||
| } | ||
| // </BodyMembersExample> | ||
| } |
38 changes: 38 additions & 0 deletions
38
docs/csharp/language-reference/builtin-types/snippets/unions/ClassUnion.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| // <ClassUnion> | ||
| [System.Runtime.CompilerServices.Union] | ||
| public class Result<T> : System.Runtime.CompilerServices.IUnion | ||
| { | ||
| private readonly object? _value; | ||
|
|
||
| public Result(T? value) { _value = value; } | ||
| public Result(Exception? value) { _value = value; } | ||
|
|
||
| public object? Value => _value; | ||
| } | ||
| // </ClassUnion> | ||
|
|
||
| public static class ClassUnionScenario | ||
| { | ||
| public static void Run() | ||
| { | ||
| ClassUnionExample(); | ||
| } | ||
|
|
||
| // <ClassUnionExample> | ||
| static void ClassUnionExample() | ||
| { | ||
| Result<string> ok = new Result<string>("success"); | ||
| Result<string> err = new Result<string>(new InvalidOperationException("failed")); | ||
|
|
||
| Console.WriteLine(Describe(ok)); // output: OK: success | ||
| Console.WriteLine(Describe(err)); // output: Error: failed | ||
|
|
||
| static string Describe(Result<string> result) => result switch | ||
| { | ||
| string s => $"OK: {s}", | ||
| Exception e => $"Error: {e.Message}", | ||
| null => "null", | ||
| }; | ||
| } | ||
| // </ClassUnionExample> | ||
| } |
35 changes: 35 additions & 0 deletions
35
docs/csharp/language-reference/builtin-types/snippets/unions/GenericUnion.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| // <GenericUnion> | ||
| public record class None; | ||
| public record class Some<T>(T Value); | ||
| public union Option<T>(None, Some<T>); | ||
| // </GenericUnion> | ||
|
|
||
| public static class GenericUnionScenario | ||
| { | ||
| public static void Run() | ||
| { | ||
| GenericUnionExample(); | ||
| } | ||
|
|
||
| // <GenericUnionExample> | ||
| static void GenericUnionExample() | ||
| { | ||
| Option<int> some = new Some<int>(42); | ||
| Option<int> none = new None(); | ||
|
|
||
| var result = some switch | ||
| { | ||
| Some<int> s => $"Has value: {s.Value}", | ||
| None => "No value", | ||
| }; | ||
| Console.WriteLine(result); // output: Has value: 42 | ||
|
|
||
| var result2 = none switch | ||
| { | ||
| Some<int> s => $"Has value: {s.Value}", | ||
| None => "No value", | ||
| }; | ||
| Console.WriteLine(result2); // output: No value | ||
| } | ||
| // </GenericUnionExample> | ||
| } |
37 changes: 37 additions & 0 deletions
37
docs/csharp/language-reference/builtin-types/snippets/unions/ManualUnion.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| // <ManualBasicPattern> | ||
| [System.Runtime.CompilerServices.Union] | ||
| public struct Shape : System.Runtime.CompilerServices.IUnion | ||
| { | ||
| private readonly object? _value; | ||
|
|
||
| public Shape(Circle value) { _value = value; } | ||
| public Shape(Rectangle value) { _value = value; } | ||
|
|
||
| public object? Value => _value; | ||
| } | ||
|
|
||
| public record class Circle(double Radius); | ||
| public record class Rectangle(double Width, double Height); | ||
| // </ManualBasicPattern> | ||
|
|
||
| public static class ManualUnionScenario | ||
| { | ||
| public static void Run() | ||
| { | ||
| ManualUnionExample(); | ||
| } | ||
|
|
||
| // <ManualUnionExample> | ||
| static void ManualUnionExample() | ||
| { | ||
| Shape shape = new Shape(new Circle(5.0)); | ||
|
|
||
| var area = shape switch | ||
| { | ||
| Circle c => Math.PI * c.Radius * c.Radius, | ||
| Rectangle r => r.Width * r.Height, | ||
| }; | ||
| Console.WriteLine($"{area:F2}"); // output: 78.54 | ||
| } | ||
| // </ManualUnionExample> | ||
| } |
36 changes: 36 additions & 0 deletions
36
docs/csharp/language-reference/builtin-types/snippets/unions/MemberProvider.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| // Uncomment when union member providers are available in the compiler: | ||
|
|
||
| // <MemberProvider> | ||
| // [System.Runtime.CompilerServices.Union] | ||
| // public record class Outcome<T> : Outcome<T>.IUnionMembers | ||
| // { | ||
| // private readonly object? _value; | ||
| // | ||
| // private Outcome(object? value) => _value = value; | ||
| // | ||
| // public interface IUnionMembers | ||
| // { | ||
| // static Outcome<T> Create(T? value) => new(value); | ||
| // static Outcome<T> Create(Exception? value) => new(value); | ||
| // object? Value { get; } | ||
| // } | ||
| // | ||
| // object? IUnionMembers.Value => _value; | ||
| // } | ||
| // </MemberProvider> | ||
|
|
||
| // <MemberProviderExample> | ||
| // public static class MemberProviderScenario | ||
| // { | ||
| // public static void Run() | ||
| // { | ||
| // Outcome<string> ok = "success"; | ||
| // var msg = ok switch | ||
| // { | ||
| // string s => $"OK: {s}", | ||
| // Exception e => $"Error: {e.Message}", | ||
| // }; | ||
| // Console.WriteLine(msg); | ||
| // } | ||
| // } | ||
| // </MemberProviderExample> |
70 changes: 70 additions & 0 deletions
70
docs/csharp/language-reference/builtin-types/snippets/unions/NonBoxingAccess.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| // <NonBoxingAccessPattern> | ||
| [System.Runtime.CompilerServices.Union] | ||
| public struct IntOrBool : System.Runtime.CompilerServices.IUnion | ||
| { | ||
| private readonly int _intValue; | ||
| private readonly bool _boolValue; | ||
| private readonly byte _tag; // 0 = none, 1 = int, 2 = bool | ||
|
|
||
| public IntOrBool(int? value) | ||
| { | ||
| if (value.HasValue) | ||
| { | ||
| _intValue = value.Value; | ||
| _tag = 1; | ||
| } | ||
| } | ||
|
|
||
| public IntOrBool(bool? value) | ||
| { | ||
| if (value.HasValue) | ||
| { | ||
| _boolValue = value.Value; | ||
| _tag = 2; | ||
| } | ||
| } | ||
|
|
||
| public object? Value => _tag switch | ||
| { | ||
| 1 => _intValue, | ||
| 2 => _boolValue, | ||
| _ => null | ||
| }; | ||
|
|
||
| public bool HasValue => _tag != 0; | ||
|
|
||
| public bool TryGetValue(out int value) | ||
| { | ||
| value = _intValue; | ||
| return _tag == 1; | ||
| } | ||
|
|
||
| public bool TryGetValue(out bool value) | ||
| { | ||
| value = _boolValue; | ||
| return _tag == 2; | ||
| } | ||
| } | ||
| // </NonBoxingAccessPattern> | ||
|
|
||
| public static class NonBoxingAccessScenario | ||
| { | ||
| public static void Run() | ||
| { | ||
| NonBoxingExample(); | ||
| } | ||
|
|
||
| // <NonBoxingExample> | ||
| static void NonBoxingExample() | ||
| { | ||
| IntOrBool val = new IntOrBool((int?)42); | ||
|
|
||
| var description = val switch | ||
| { | ||
| int i => $"int: {i}", | ||
| bool b => $"bool: {b}", | ||
| }; | ||
| Console.WriteLine(description); // output: int: 42 | ||
| } | ||
| // </NonBoxingExample> | ||
| } | ||
44 changes: 44 additions & 0 deletions
44
docs/csharp/language-reference/builtin-types/snippets/unions/NullHandling.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| public static class NullHandlingScenario | ||
| { | ||
| public static void Run() | ||
| { | ||
| NullHandling(); | ||
| NullableUnionExample(); | ||
| } | ||
|
|
||
| // <NullHandling> | ||
| static void NullHandling() | ||
| { | ||
| Pet pet = default; | ||
| Console.WriteLine(pet.Value is null); // output: True | ||
|
|
||
| var description = pet switch | ||
| { | ||
| Dog d => d.Name, | ||
| Cat c => c.Name, | ||
| Bird b => b.Name, | ||
| null => "no pet", | ||
| }; | ||
| Console.WriteLine(description); // output: no pet | ||
| } | ||
| // </NullHandling> | ||
|
|
||
| // <NullableUnionExample> | ||
| static void NullableUnionExample() | ||
| { | ||
| Pet? maybePet = new Dog("Buddy"); | ||
| Pet? noPet = null; | ||
|
|
||
| Console.WriteLine(Describe(maybePet)); // output: Dog: Buddy | ||
| Console.WriteLine(Describe(noPet)); // output: no pet | ||
|
|
||
| static string Describe(Pet? pet) => pet switch | ||
| { | ||
| Dog d => d.Name, | ||
| Cat c => c.Name, | ||
| Bird b => b.Name, | ||
| null => "no pet", | ||
| }; | ||
| } | ||
| // </NullableUnionExample> | ||
| } |
10 changes: 10 additions & 0 deletions
10
docs/csharp/language-reference/builtin-types/snippets/unions/Program.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| BasicUnionScenario.Run(); | ||
| GenericUnionScenario.Run(); | ||
| ValueTypeCasesScenario.Run(); | ||
| BodyMembersScenario.Run(); | ||
| NullHandlingScenario.Run(); | ||
| ManualUnionScenario.Run(); | ||
| NonBoxingAccessScenario.Run(); | ||
| ClassUnionScenario.Run(); | ||
| // Uncomment when union member providers are available in the compiler: | ||
| // MemberProviderScenario.Run(); |
13 changes: 13 additions & 0 deletions
13
docs/csharp/language-reference/builtin-types/snippets/unions/RuntimePolyfill.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| // Remove this file when UnionAttribute and IUnion are included in the .NET runtime. | ||
| // <RuntimePolyfill> | ||
| namespace System.Runtime.CompilerServices | ||
| { | ||
| [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)] | ||
| public sealed class UnionAttribute : Attribute; | ||
|
|
||
| public interface IUnion | ||
| { | ||
| object? Value { get; } | ||
| } | ||
| } | ||
| // </RuntimePolyfill> |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.