Compiler allows Nullable function to return Not Nullable value #8250
Replies: 2 comments
-
This is by design. All types are implicitly convertible to the nullable version of that type.
Correct. The
You've used |
Beta Was this translation helpful? Give feedback.
-
If your method has a nullable value type return type, and all returns have a known not-null value, it is indeed a potential source of bugs. You can write an analyzer which would warn in those situations. For |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
When designing a function with a nullable return value, the compiler stays quiet about trying to return a not nullable value, as this:
This function signature states a function that returns a Nullable.
In my vision, the compiler should throw the same casting error when doing the opposite:
Cannot implicitly convert type 'long?' to 'long'. An explicit conversion exists (are you missing a cast?)
Motivation for this proposal:
The following function returns 0, instead of null:
But this one returns null:
Environment: macOS Air M2
dotnet 8
Beta Was this translation helpful? Give feedback.
All reactions