Replies: 1 comment
-
@jcouv do you recall if this behavior is by design? (whether nullability attributes on a delegate affect initial state of lambda parameters.) |
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
-
I have an extension method that can be used to map a value to another value if the original one isn't
null
:So it can be used like this for example:
What I expected was for the compiler to be able to detect that
s
isn't supposed to benull
inside the lambda based onDisallowNull
attribute. Interestingly enough, Rider and probably Resharper are able to do this and they don't show any warnings. However, that's not the case when building a project - in this situation, the compiler gives warning CS8602: Dereference of a possibly null reference. It's possible to fix that problem by changingMapIfNotNull
to this:I understand why this code works after the change but I'm not sure why it doesn't before, especially since other tools are able to correctly identify that
NotNullMapping
parameter shouldn't benull
.Additionally when
IEnumerable<string>
is changed toIEnumerable<int?>
the original version withDisallowNull
works correctly in Rider but again the compiler gives CS8602 and now also CS8622 - Nullability of reference types in type of parameter doesn't match the target delegate (possibly because of nullability attributes). Unfortunately in that case the fix withnotnull
doesn't work anymore.Obviously, the compiler doesn't need to work the same way Rider does but in that case Rider's behaviour seems to be more reasonable, though that might not be a correct impression.
The other way to have no warning is to explicitly declare the type of lambda parameter to be non-nullable:
Unfortunately, it also means that this type is marked as redundant.
My question is: why doesn't original version work and is this something that could be improved or changed in the compiler? If not then I'd probably report that as a bug in Rider since those hidden warnings make working with NRT more cumbersome.
Beta Was this translation helpful? Give feedback.
All reactions