[Proposal]: Allow with
keyword for classes containing constructor expecting itself
#8247
Replies: 3 comments 2 replies
-
Sorry, saw that a discussion needs to be created first just now, any maintainer please feel free to convert this to a discussion. |
Beta Was this translation helpful? Give feedback.
-
How would the compiler know that such a constructor is a “copy constructor”? Consider With |
Beta Was this translation helpful? Give feedback.
-
In my opinion this is one of the key problems to think about. The The problem with using the constructor is that there is no virtual dispatch so it will not work polymorphically: public class Person { ... }
public class PersonWithAge(string firstName, string lastName, int age)
: Person(firstName, lastName)
{
public int Age { get; } = age;
}
Person person1 = new PersonWithAge("Jared", "Parsons", TooOld);
var person2 = person1 with { LastName = "Oops" }; In this case the The idea of generalizing this to all classes was discussed when we did
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Allow
with
keyword for classes containing constructor expecting itselfSummary
Enable the use of the
with
keyword for classes that contain a constructor expecting an instance of the same class, allowing for non-destructive mutation similar to records.Motivation
Currently, the
with
keyword is only available for record types in C#. This proposal aims to extend this functionality to regular classes, given that they have a constructor that takes an instance of the same class. This will enable developers to create new instances of a class with modified properties without affecting the original instance, promoting immutability and reducing boilerplate code.Detailed design
Syntax
The syntax for using the
with
keyword in classes will be similar to that in records:Semantics
with
expression creates a new instance of the class.Person(Person other)
in the example above) to copy properties from the original instance.with
expression are modified; all other properties are copied from the original instance.Specification Changes
Changes are required in the following sections of the C# language specification:
with
keyword for classes.with
keyword, specifically the need for a constructor that takes an instance of the same class.Drawbacks
Alternatives
Unresolved questions
ICloneable
be used?Design meetings
None yet.
Beta Was this translation helpful? Give feedback.
All reactions