-
Take a tree structure where a hierarchy of types are needed (i.e. not flat). How would you define such tree using records?
Using classes, there's much boilerplate code to write. I'm particularly interested to see how records could improve that. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Can you explain this bit:
so abstract nodes can contain data. But leafnodes (which are, aren't abstractnodes?) can/cannot? |
Beta Was this translation helpful? Give feedback.
-
Turns out, simply using 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 singletons out-of-the-box (LeafNode2 example above). |
Beta Was this translation helpful? Give feedback.
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.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…