Nullable backing field
when explicitely annotated
#9279
Unanswered
Rubidium37
asked this question in
Language Ideas
Replies: 2 comments
-
Nullable value type is a different type. It can't be affected by annotation attributes, which only affects nullable reference type. Declaring the backing field with a different type is out of scope currently. Issues in csharplang repo are reserved for language design team. Please use discussions to express ideas. |
Beta Was this translation helpful? Give feedback.
0 replies
-
#133 would provide one solution to this, where you would write: public class C
{
public int TodayYear { int? field; get => field ??= DateTime.Today.Year; }
} |
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.
Uh oh!
There was an error while loading. Please reload this page.
-
Nullable backing
field
when explicitely annotatedfield
keyword in properties #8635Summary
I'm actively using the
field
keyword in my projects.I'm using it both with class types and values types.
I found out that a possible feature is missing: having the backing field nullable even when the property is not.
It somehow already works for class types, by adopting nullable reference types annotations.
It is not supported for value types.
It would be nice if the specification will include some practice (attribute annotation, explicit field type declaration, etc..) to specify the type of the backing field as nullable.
If a code generator is involved to generate the backing field, than it would be enough to append the
?
symbol after the type when generating code, if (and only if) theMaybeNull
attribute is annotated.To make it clear, below you can find two code samples that depict the use case.
Code samples
int
).field
keyword.Minimal code:
Expected Behavior:
The code should compile fine.
I expect that the
MaybeNull
attribute and/or the coalesce assignment operator (??=
) hint the compiler to make the backing field nullable; that is,Nullable<int>
.Thus, it should produce something equivalent to:
Actual Behavior:
I get compiler error CS0019: Operator '??=' cannot be applied to operands of type 'int' and 'int'
For comparison, you can try the code snippet on Sharplab IO
It show both the ideal code and the manually implemented equivalent.
Beta Was this translation helpful? Give feedback.
All reactions