[Proposal]: MemberNotNullWhen
on parameters
#9619
Unanswered
logiclrd
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.
-
MemberNotNullWhen
on parametersSummary
The existing compiler attributes
MemberNotNullWhen
allows declaring that a member of the type is guaranteed to be not null if the return value of a function has the specified value. It is proposed that this attribute be permitted on arguments to unctions and constructors as well.Motivation
In the following example, the returned
Class
instance has a fieldName
which could benull
. But, if theassignName
parameter to the constructor istrue
, thenName
will always be non-null. There is no way to tell this to the compiler.With the proposed attribute usage, the compiler would know the behaviour of the constructor (or function) and could mark the field of the object as not
null
.Detailed design
I don't know the internals of how the analyzer works. However, the fact that
MemberNotNullWhen
can be used today on return values in a very similar analysis graph suggests that it would perhaps not be difficult to add this functionality.Drawbacks
I don't see any language-related issues.
Alternatives
The only workarounds I'm aware of right now are either to make the either field not
null
or to hint to the analyzer that you know it to be notnull
, either with an explicit runtime check or with the!
null-forgiving operator.These are not ideal. They clutter up the source code, explicitly override otherwise-useful analysis, and also, in the case of the first work-around, have a small impact on runtime performance.
Unresolved questions
Design meetings
Beta Was this translation helpful? Give feedback.
All reactions