Skip to content

How to define discriminated unions using records? #47358

Answered by alrz
alrz asked this question in General
Discussion options

You must be logged in to vote

Turns out, simply using record will do the job. If you don't want to deal with base constructor call, you can define fields rather than arguments in primary ctor and value equality still works.

abstract record RootNode {
  public object Data;
  sealed record LeafNode1 : RootNode {
    public int Left, Right;
  }
  sealed record LeafNode2 : RootNode { }
}

To make sure every field gets initialized we probably need dotnet/csharplang#3630

Now the only downside to this is that every field is taken into account for value equality and there is no easy workaround to exclude some except for redefining Equals and GetHashCode completely.

Also it would be nice if empty records gets compiled to single…

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
3 replies
@alrz
Comment options

alrz Sep 3, 2020
Collaborator Author

@svick
Comment options

@alrz
Comment options

alrz Sep 3, 2020
Collaborator Author

Comment options

alrz
Sep 7, 2020
Collaborator Author

You must be logged in to vote
0 replies
Answer selected by alrz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
3 participants