Proposal: Allow partial method implementations to assign readonly fields #1171
Unanswered
daiplusplus
asked this question in
General
Replies: 3 comments
-
This would require that the compiler inline the body of the |
Beta Was this translation helpful? Give feedback.
0 replies
-
Yes, I believe that would be correct behaviour in this case if the CLR enforced |
Beta Was this translation helpful? Give feedback.
0 replies
-
Loosely related: #348 |
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.
-
Problem:
By-design
readonly
fields can only be assigned in their containing type's constructor. This becomes an issue when apartial class
's constructor is outside of the programmer's control (e.g. a T4-generated or Designer-generated constructor). A good example is an MVVM ViewModel withreadonly RelayCommand
properties:CalculatorViewModel.generated.cs:
CalculatorViewModel.cs:
With this arrangement the programmer is unable to add new
readonly
fields toCalculatorViewModel
because the single constructor is in the generated file and any changes will be overwritten during the next build.Proposed solution
As
partial
methods are a design-time syntactic concern thereadonly
correctness checks can still be maintained while allowing assignment toreadonly
members.The constructor would still be in the
generated.cs
file, except the generated constructor would call a new partial method (just like WinFormsInitializeComponent
) except thatreadonly
assignment is now allowed provided the partial method is only called from a constructor:CalculatorViewModel.generated.cs:
CalculatorViewModel.cs:
The compiler would internally tag any
partial void
methods asalters-readonly
as it encounters them and then prohibit calling them from outside a constructor, and the compiler would then use this tag to prove that inlining the partial void implementation is correct. I understand the semantics ofpartial void
means that inlining does not result in any change in program behaviour.CalculatorViewModel.cs:
Beta Was this translation helpful? Give feedback.
All reactions