Records with internal readonly fields/properties derived from constructor should initialise within the constructor #7941
Unanswered
Jeltz191
asked this question in
Language Ideas
Replies: 0 comments
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.
-
I often use a record construct to pre-calculate variables that are used multiple times within the records methods (see example below). Currently line 4 is disallowed (CS0236), but if placed in a traditional constructor it becomes perfectly acceptable. Changing the initializer to a lambda method defeats the efficiency improvements, and changing to an old-style constructer just bloats the code.
public record test(int j1, int j2)
{
private readonly int q2 = 2 * j1 + j2 * j2; //pre-calculate
private readonly int q3=q2*j1; //currently not allowed!!!!
// private readonly int q3=(2 * j1 + j2 * j2)j // allowed but inefficient and less readable
// private readonly int q3=>q2j1; //allowed but defeats the purpose of improving efficiency.
public (int, int) Method(int j3) //Method made more efficient due to pre-calculation
{
return (q2 + j2 * j3, q2 * j3 + j2);
}
}
Beta Was this translation helpful? Give feedback.
All reactions