[Proposal] null guards for nullable types #828
Replies: 8 comments
-
It would cause existing code to change semantics if the compiler would treat public void M(int? value) { ... }
public void M(int value) { ... }
public void Test(int? value) {
if (value != null) {
M(value);
}
} |
Beta Was this translation helpful? Give feedback.
-
Yeah, I see your point. But that is a very strange use case though. |
Beta Was this translation helpful? Give feedback.
-
This could be more specific. When the return type is Flow analysis could provide a warning when it could be null. |
Beta Was this translation helpful? Give feedback.
-
@bondsbw you mean this case: private int Test(int? value)
{
if (value != null)
{
return _value;
}
return 0;
} Yes, that is probably less likely to break something |
Beta Was this translation helpful? Give feedback.
-
@mariusGundersen where are you taking it from? There is not |
Beta Was this translation helpful? Give feedback.
-
sorry, yes, I meant this, which also does not compile because private int Test(int? value)
{
if (value != null)
{
return value;
}
return 0;
} |
Beta Was this translation helpful? Give feedback.
-
@bondsbw why should it works for return values only? And what's about multithreading? If it's not a local for example:
what happens if another thread is changing the value between null check and return? If we limit its usage for locals only it becomes almost useless feature. I don't think we need this. Unfortunly, we are not TypeScript developers where it works :) If you don't want to write it twice you always can do:
I'd prefer operators to being working with null propagation (as method calls, for example):
which is the equivalent of:
|
Beta Was this translation helpful? Give feedback.
-
If implicit casting can work for other cases without running into the problems @HaloFour pointed out, I would agree with considering those cases.
This was discussed in another thread related to nullability flow analysis. I believe the idea is that the feature is useful even if it's not perfect (and it should not be advertised as perfect). |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
The following code does not compile:
It should be clear to the compiler that inside the truthy branch of the if statement
value
is of typeint
, notint?
, and that after the if statement it isnull
. This would be only of slight usage for the current nullable types, but with the next version of C# where everything can be nullable this would be of greater value.This would be sugar for the following:
Beta Was this translation helpful? Give feedback.
All reactions