Skip to content

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

Open
@TessenR

Description

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 ??= "";
    };

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions