Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Roslyn incorrectly learns from [NotNullIfNotNull] attributes that mention out parameters #52438

Open
TessenR opened this issue Apr 6, 2021 · 0 comments

Comments

@TessenR
Copy link

TessenR commented Apr 6, 2021

Version Used:

Branch main (3 Apr 2021)
Latest commit 3a30d52 by CyrusNajmabadi:
Merge pull request #52392 from Youssef1313/add-imports-null-check-code-fix

Import System namespace when adding null check

Steps to Reproduce:

Compile and run the following code:

using System.Diagnostics.CodeAnalysis;

#nullable enable
C.M1(out _).ToString(); // no warnings; runtime crash

class C
{
  [return: NotNullIfNotNull("arg")] public static string? M1(out string? arg) => arg = null;
}

Expected Behavior:
CS8602: Dereference of a possibly null reference. warning for C.M1(out _)

Actual Behavior:
No warnings at all in the program above. The program crashes with NullReferenceException at runtime

Notes
It looks like Roslyn tries to learn the resulting nullability from the argument state of an out parameter e.g. the following code also doesn't have a warning:

string s = "";
C.M1(out s!).ToString();

Obviously it's impossible to introduce a dependency on the out argument state since the compiler won't allow reading it from the annotated method.

This might be confusing since it's not immediately obvious that nullable reference types don't support dependencies between variables so someone could attempt to use this attribute to e.g. introduce a dependency between related out parameters (e.g. if multiple out parameters always have the same nullable state when a method returns)

@dotnet-issue-labeler dotnet-issue-labeler bot added Area-Compilers untriaged Issues and PRs which have not yet been triaged by a lead labels Apr 6, 2021
@jaredpar jaredpar added Bug New Language Feature - Nullable Reference Types Nullable Reference Types and removed untriaged Issues and PRs which have not yet been triaged by a lead labels Apr 20, 2021
@jaredpar jaredpar added this to the C# 10 milestone Apr 20, 2021
@jaredpar jaredpar added this to Nullability attributes (C# 9) in Nullable Board Apr 20, 2021
@jaredpar jaredpar modified the milestones: C# 10, 17.0 Jul 13, 2021
@jaredpar jaredpar modified the milestones: 17.0, 17.1 Aug 3, 2021
@jinujoseph jinujoseph modified the milestones: 17.1, 17.3 Apr 27, 2022
@jaredpar jaredpar modified the milestones: 17.3, Backlog Jun 30, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Nullable Board
Nullability attributes (C# 9)
Development

No branches or pull requests

3 participants