Proposal: Automatic null-checking for generic parameters with notnull constraint #9363
Unanswered
paulinhps
asked this question in
Language Ideas
Replies: 2 comments 1 reply
-
C# doesn't insert any |
Beta Was this translation helpful? Give feedback.
1 reply
-
The automatic null check operator was reverted from C# 11 due to feedback: #5735 |
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.
-
Proposal: Automatic null-checking for generic parameters with
notnull
constraintSummary
The
notnull
constraint for generic parameters currently only provides compile-time checking, but doesn't guarantee runtime safety against null values. This proposal suggests automatically injecting null-checking code (similar toArgumentNullException.ThrowIfNull()
) for parameters with thenotnull
constraint to improve runtime safety and align developer expectations with actual behavior.Problem
The
notnull
constraint tells the compiler that a generic type parameter should not be nullable. However, this only affects compile-time checking. There are ways to bypass this constraint and pass null values at runtime:null!
)Consider this example:
Despite the
notnull
constraint, the code compiles and would only fail at runtime with a potentially confusingNullReferenceException
when the code tries to use the null value, rather than a clearArgumentNullException
indicating the problem immediately.Proposed Solution
Enhance the C# compiler to automatically inject null-checking code at the beginning of methods that have generic parameters with the
notnull
constraint.For example, given:
The compiler would implicitly transform this to behave as if it were written:
Benefits
NullReferenceException
by failing fast with clearArgumentNullException
notnull
parametersnotnull
constraint prevents null values at both compile-time and runtimePrecedents
There are precedents for compiler-injected null checks in C#:
Potential Concerns
Compatibility
This change would be backward compatible, as it would only prevent behavior that is conceptually incorrect according to the constraint's intent.
Alternative Approaches
strictnotnull
that includes runtime checkingI believe the proposed automatic null-checking would be the most ergonomic and safe option that aligns with developer expectations.
Questions for Discussion
Thank you for considering this proposal.
Beta Was this translation helpful? Give feedback.
All reactions