[Proposal]: allow copying using "with" keyword with regular classes #9257
Unanswered
Aziz-Dhiab
asked this question in
Language Ideas
Replies: 1 comment
-
See: #8876 I believe the biggest problem around adopting this for normal classes is enforcing the correct pattern for cloning the instance. A record emits a special "unspeakable" clone method, which is virtual and must be implemented by every type that derives from that record. The compiler would need to enforce a similar pattern for non-records. This method can't be a copy constructor because the compiler would not know the actual type of the instance at compile time, thus would call the constructor on the base type resulting in decapitation: Person person = new Student() { ... };
Person clone = person with { ... };
Debug.Assert(clone is Student); // oops, the clone is not a Student since the Person constructor was called |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
Currently, the with keyword in C# is restricted to records, allowing for non-destructive mutation by creating a shallow copy with modified properties. This proposal suggests extending with to regular classes, making object copying and modifications more concise and expressive using already existing syntax.
Motivation
Improved Readability & Maintainability: The with syntax is more concise and readable than using a clone method and changing some property or using some workaround like this example
Records are great but there are a lot of situation where the user doesn't want value semantics on a class but copying using with keyword would greatly benefit in copying scenarios.
Drawbacks
Potential confusion: maybe only allow this if the class have a regular copy constructor.
Beta Was this translation helpful? Give feedback.
All reactions