[Proposal][C# 9.0 / .NET 5.0] "with" expression as one-shot initializer #4070
-
In order to augment the productivity when using LINQ to Entities. please implement with-expression not as property modification after cloning instance but as one-shot initializer. When a new record object is defined with some of properties modified and the others copied from another
the preview version of C# 9.0 compiler or .NET 5.0 RC2 seems to interpret, inside of it, Expression (A) as follows:
However, I think it has to be interpreted instead as follows:
This is because the interpretation as Expression (B) causes an error CS8849(*) due to the procedural substitution "rec2.PropC = 0;" obstructing compilation to an expression tree so as not to work on IQueryable<T> or LINQ to Entities, even though it can work well on IEnumerable<T> or LINQ to Object. (*) error CS8849: An expression tree may not contain a with-expression. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
The Person person = new Student { Name = "John Smith", Grade = 4.0 };
// somewhere else in code
var clone = person with { Name = "John Jones" };
Assert.IsTrue(clone is Person { Name: "John Jones", Grade: 4.0 }); The instance method is responsible for returning the correct type regardless of the source type and to initialize the internal state of the source type beyond what the initializer would be able to initializer. Like most new language features it's unlikely it will work with expression trees. |
Beta Was this translation helpful? Give feedback.
-
What I have been expected of with-expression, for a long time, is to behave not as an instance method but as a pure record object initializer. Since I wrote in C# 7, as follows, an expanded Clone() method to do the same thing as with-expression does and it has been working well on LINQ to Object, the current function of with-expression is just a slightly simplified substitute if it clones an instance and then rewrites some properties to work as an instance method.
When someone rejects my proposal, all I need is a reasonable clarification why with-expression cannot be implemented as a pure initializer. |
Beta Was this translation helpful? Give feedback.
What I have been expected of with-expression, for a long time, is to behave not as an instance method but as a pure record object initializer.
Since I wrote in C# 7, as follows, an expanded Clone() method to do the same thing as with-expression does and it has been working well on LINQ to Object, the current function of with-expression is just a slightly simplified substitute if it clones an instance and then rewrites some properties to work as an instance method.
var rec2 = rec1.Clone(new { PropC = 0 }) as MyRecord; // C# 7 notation equivalent to Expression (A)
When someone rejects my proposal, all I need is a reasonable clarification why with-expression cannot be implemented as a pure i…