Proposal: Qualifier on variables to make fields of that variable immutable via that reference #5205
Unanswered
bclehmann
asked this question in
Language Ideas
Replies: 1 comment 1 reply
-
This is an interesting idea but I'd need to hear a lot more details as to how this would be enforced. This would seemingly be very easy to defeat through any means of indirection given that neither the language nor the runtime can track this "sealed"-ness across any API boundaries.
This might help mitigate the above, but it also makes the reference nearly unusable through the rest of the .NET ecosystem. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Example and Explanation
For the sake of this example I will reuse the
sealed
keyword, but I am not set on this keyword. Especially as it may collide with existing uses of that keyword.Suppose we have code like this:
Any attempt to modify the fields of
Foo.data
through theFoo.data
reference outside of a constructor or initializer should be a compile-time error. Modifying the reference ofFoo.data
(i.e. assigning it to another object) should be allowed unlessreadonly
,const
, or an init-only setter is specified. Modifying the fields ofFoo.data
through another reference that is not qualified withsealed
shall be allowed.Range
This qualifier is to be valid on variable declarations, class/struct/record field or property declarations, and return types of functions and methods.
Use in
Func
orAction
style delegates would be nice, but I could anticipate that being more difficult to implement.Inspiration
This was inspired by the difference between these in C/C++:
const Foo*
int* const
Motivation
The principle of encapsulation is damaged if a class' member variables can be modified from outside the class. With this suggestion a class can now return a reference which does not have write access:
With the
sealed
qualifier, code like this will no longer compile:For what it's worth, it's probably wise to add a shorthand to getter syntax here so we don't need to write getters by hand to use this keyword:
Extras
One should not be able to convert from a
sealed
qualified object to an unqualified object. One should be able to implicitly convert the other way.This suggestion was intentionally made so it could be implemented as a compile-time check. However, it could be interesting to designate an object's fields immutable through any reference (or any reference but one) dynamically. This could be used to enforce a class' ownership of a resource.
Beta Was this translation helpful? Give feedback.
All reactions