Nullable Value Type property enhancements. #9285
Unanswered
franchyd
asked this question in
Language Ideas
Replies: 1 comment 5 replies
-
Beta Was this translation helpful? Give feedback.
5 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.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
Introduce syntax for properties that allow a nullable setter/init and a non-nullable getter for value types. This enables clean patterns where a property may accept or start as null but will always return a value.
Motivation
A common pattern in real-world development is to have a property that accept null (e.g., during deserialization, configuration, or delayed assignment), but never return null to consumers.
This is easily achieved with Reference types, but for value types, this requires verbose manual backing fields and a function:
Proposed Syntax
Semantics
If using an auto-property, the backing field is nullable
An explicit getter implementation is always required (as otherwise it could return null).
Pros
Cons
Further thoughts
Should a nullable set be able to implement a non-nullable set from an interface:
It would be on par with NRTs capabilities to do so, however as NVT's are different runtime types than non-nullable value types it would be a different signature and would require a hidden non-nullable proxy "set" to be generated by the compiler.
How do you declare a nullable backing field when you don't want a nullable set.
Its a bit against current patterns to have both a setter and an init accessor. Alternatively in this scenario(or a getter only scenario) the compiler could infer the nullability of the backing field from the getter’s implementation. However this is also counter to current language concepts in that slight changes to the getter can transform the type of the backing field.
Beta Was this translation helpful? Give feedback.
All reactions