3

Reading through the spec for C# 9.0 I came across record and the new with expression. Immediately I thought this was great for all my immutable structs, such as vectors and matrices! However it turns out that the with expression only works on records. How come? Does the with expression require something that only a record is guaranteed to have (equality members perhaps)?

I can understand the argument that structs don't need it since they are value types and simply assigning the value to a new variable is enough to create a copy, but the syntax would be nice and surely it would be useful to create copies like that even for normal classes, not just records?

Charanor
  • 810
  • 8
  • 23
  • 2
    `with` expressions use the protected `$` method. Non-record types can't declare such a method. I wrote a bit about the boilerplate code in my answer [here](https://stackoverflow.com/a/65422383/5394572). – madreflection Dec 31 '20 at 22:18
  • "*How come?*" questions are not very satisfying for anyone. The only valid answer is "*because it does*" Yes sure there is usually a discussion trail to these language features, but it will be hit and miss if they can address a specific question like this. Secondly, asking why they didn't implement further features is futile, maybe they didn't think of it, maybe it would require too many changes, maybe its just a bad idea and it was never discussed. In the end this question because too broad, and opinion based – TheGeneral Jan 01 '21 at 02:16
  • *"Does the with expression require something that only a record is guaranteed to have?"* is a pretty concrete question, though. The title isn't always the actual question. I'm not sure if the answer I linked actually answers the question so I didn't flag it; if it does, it does so indirectly. – madreflection Jan 01 '21 at 02:18
  • 1
    @madreflection agreed, but there is more to unpack here, and several musings and sub questions in play. The perfect answer by Eric Lippert https://stackoverflow.com/a/8673015/1612975 – TheGeneral Jan 01 '21 at 02:22
  • FYI: C# 10 now allows with expressions on all structs. – Mike Christiansen Mar 04 '23 at 14:14

0 Answers0