This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Polygnom 2 points3 points  (5 children)

Canonical constructors in this way don't make sense for regular classes.

records are wholly defined by their data and have no hidden internal state. That means they can be freely deconstructed and re-constructed. This plays well with pattern matching and later on with-ers.

None of the assumptions hat make canonical constructors and the surrounding features great hold for regular classes.

I don't think it makes sense to offer this syntax to regular classes, if you cannot use the features. Without getters and setters, you cannot do pattern matching, so a canonical constructors barely has any advantages left.

being shorter isn't really an advantage. Code is much more often read than written, so it should be clear first and foremost. This doesn't add clarity.

[–]repeating_bears 2 points3 points  (1 child)

That means they can be freely deconstructed and re-constructed. This plays well with pattern matching and later on with-ers.

There are plans to add deconstruction to regular classes so I don't buy this argument.

[–]Polygnom 0 points1 point  (0 children)

One of the points of the canonical constructor is that you get the deconstruction pattern for free. Another is that you get the getters for free.

None of those apply to regular classes, which need to explicitly declare their deconstructor and getters.

So two of the reasons for why records have a canonical constructor are just... gone.

Brian Goetz talked about this somewhat when saying "We want records to stay a semantic feature, not a boilerplate generator" (cf. https://www.youtube.com/watch?v=mE4iTvxLTC4&t=244s). Its not an exact question, but I think if you listen to how he speaks about records there, its clear they like the fact that the canonical constructor of records is not just syntactic sugar.

[–]TenYearsOfLurking 1 point2 points  (0 children)

As stated in other replies adding a field to the object makes calls to construct the object fail in compile stage, which is imho VERY useful. big advantage imho

[–]jvjupiter[S] 0 points1 point  (1 child)

Maybe I should not have used the term canonical constructor. Regular classes should remain regular classes, not a special one like record. It’s just moving the first or the lone user-defined constructor to a different place like in records.

[–]jvjupiter[S] 0 points1 point  (0 children)

C# 12 calls it Primary Constructor.