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

[MemberNotNull(When)] annotations don't work on local functions inside member initializers inside non-static closure chains #76528

Open
TessenR opened this issue Dec 19, 2024 · 0 comments
Labels
Area-Compilers Feature - Nullable Reference Types Nullable Reference Types untriaged Issues and PRs which have not yet been triaged by a lead

Comments

@TessenR
Copy link

TessenR commented Dec 19, 2024

Version Used:

Branch main (19 Dec 2024)
Latest commit [395d298](https://github.com/dotnet/roslyn/commit/395d298bd9093150e41580be29c53955d2781874) by Cyrus Najmabadi:
Remove sync over async blocking in Extract Method/Interface options code (#76510)

Steps to Reproduce:

Compile the following code (sharplab.io)

using System;
using System.Diagnostics.CodeAnalysis;
#nullable enable
public class C
{
  public static string? field;

  public Action Prop1 { get; } = () =>
    {
      init();
      Console.WriteLine(field.Length); //  CS8602: Dereference of a possibly null reference.

      [MemberNotNull(nameof(field))]
      void init() => field ??= "";
    };
}

Expected Behavior:
No warning fo field.Length access in Prop1. The local function ensures that the member is not nullable and declares it in its annotation

Actual Behavior:
Incorrect CS8602 warning for Prop1

Notes:
You can get rid of the false warning by adding static to any of the closures in this example (either to the lambda itself or to the local function) e.g.

  public Action Prop1 { get; } = static () =>
    {
      init();
      Console.WriteLine(field.Length); // no warning

      [MemberNotNull(nameof(field))]
      void init() => field ??= "";
    };

However, it seems that this shouldn't be required - static only disallows closures and shouldn't affect the behavior when there are none.
[MemberNotNull(When)] doesn't require any static modifiers in other members, e.g.:

  public Action M() => () => 
    {
      init();
      Console.WriteLine(field.Length); // no warning

      [MemberNotNull(nameof(field))]
      void init() => field ??= "";
    };
@dotnet-issue-labeler dotnet-issue-labeler bot added Area-Compilers untriaged Issues and PRs which have not yet been triaged by a lead labels Dec 19, 2024
@jcouv jcouv added the Feature - Nullable Reference Types Nullable Reference Types label Dec 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Area-Compilers Feature - Nullable Reference Types Nullable Reference Types untriaged Issues and PRs which have not yet been triaged by a lead
Projects
None yet
Development

No branches or pull requests

2 participants