Skip to content

Strange behaviour of nullable references checking #3433

Answered by YairHalberstadt
ILAgent asked this question in Q&A
Discussion options

You must be logged in to vote

As an aside, bugs in null flow analysis should be opened in the roslyn repository.

However this behaviour, whilst surprising, is as expected.

Linq hasn't been annotated yet, so the compiler doesn't know first can be null. It assumes that the value returned from FirstOrDefault is not null. Specifying the type as object? doesn't change this - that only allows you to assign null to that local, but doesn't affect its flow state. Therefore it doesn't warn on first.GetType().

However, when do an explicit check for null, by calling if(first == null), the compiler assumes that you are telling it that first can be null. Therefore it warns when you later call first.GetType()

Replies: 10 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by YairHalberstadt
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants
Converted from issue

This discussion was converted from issue #3433 on November 29, 2020 08:22.