Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// <MemberProvider>
[System.Runtime.CompilerServices.Union]
public record class Outcome<T> : Outcome<T>.IUnionMembers
public struct Outcome<T> : Outcome<T>.IUnionMembers
{
private readonly object? _value;

Expand All @@ -11,9 +11,35 @@ public interface IUnionMembers
static Outcome<T> Create(T? value) => new(value);
static Outcome<T> Create(Exception? value) => new(value);
object? Value { get; }

// only when needed
bool TryGetValue(out T value);
bool TryGetValue(out Exception value);
}

object? IUnionMembers.Value => _value;

public bool TryGetValue(out T value)
{
if (_value is T t)
{
value = t;
return true;
}
value = default!;
return false;
}

public bool TryGetValue(out Exception value)
{
if (_value is Exception e)
{
value = e;
return true;
}
value = default!;
return false;
}
}
// </MemberProvider>

Expand Down
2 changes: 1 addition & 1 deletion docs/csharp/language-reference/builtin-types/union.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ The compiler prefers `TryGetValue` over the `Value` property when implementing p

### Union member providers

A union type can delegate its union members to a nested `IUnionMembers` interface. When this interface is present, the compiler looks for `Create` factory methods instead of constructors:
A union type can delegate its union members to a nested `IUnionMembers` interface. When this interface is present, the `union` type behaves as a *union member provider*. The compiler generates code to call the `IUnionMembers` interface. It won't generate calls to members declared on the union type that aren't members of the nested `IUnionMembers` interface. As the following example shows, that means you must add the necessary factory methods and the appropriate `TryGetValue` methods for all case types:

:::code language="csharp" source="snippets/unions/MemberProvider.cs" id="MemberProvider":::

Expand Down